Getting Started With Regular Expressions in Python - CNDRO.LLC
3216
post-template-default,single,single-post,postid-3216,single-format-standard,wp-custom-logo,theme-bridge,bridge-core-2.9.4,woocommerce-no-js,tribe-no-js,ehf-template-bridge,ehf-stylesheet-bridge-child,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,columns-4,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634

Getting Started With Regular Expressions in Python

Regular Expressions in Python Picture
                                                                      Photo by Alex Chumak on Unsplash


1 Got the search.

RegEx Functions

1 import re
2
3 pattern = '^I.*texas$'
4 test_string = 'I am in texas'
5 result = re.match(pattern, test_string)
6
7 if result:
8 print("Got the search.")
9 else:
10 print("Search unsuccessful.")

 

1 import re
2 # The string of text where regular expression will be searched.
3 string_1 = """Here are some cudtomer's id, Mr Joseph: 396
4 Mr Jones: 457
5 Mrs Shane: 222
6 Mr Adams: 156
7 Miss Grace: 908"""
8 # Setting the regular expression for finding digits in the string.
9 regex_1 = "(\d+)"
10 match_1 = re.findall(regex_1, string_1)
11 print(match_1)

 

1 ['396', '457', '222', '156', '908']

 

1
2import re
3
4s = 'what school did you graduated from?'
5
6match = re.search(r'school', s)
7
8print('Start Index:', match.start()) 9print('End Index:', match.end())

 

1 Start Index: 5 
2 End Index: 11
1 import re
2
3#the pattern sequence for hyphen or non alphanumeric chracter 4pattern = r'\W+'
5
6# our targeted string
7string = "100-joe-01-10-2022"
8
9#we want to split the string by the first 2 hyphens
10txt_ = re.split(pattern, string, maxsplit=2)
11
12print(txt_)

 

1 ['100', 'joe', '01-10-2022']
1 import re
2
3 # Our Given String
4 s = "Debugging is very important when coding."
5
6 # Performing the Sub() operation
7 out_1 = re.sub('a', 'x', s)
8 out_2 = re.sub('[a,I]','x',s)
9 out_3 = re.sub('very','not',s)
10
11 # Print output
12 print(out_1)
13 print(out_2)

 

1 Debugging is very importxnt when coding.
2 Debugging is not important when coding.

 

Python RegEx Meta Characters

No Comments

Post A Comment