0

I'm having trouble finding the appropriate regex pattern to that will match each variation of the following:

regular expression  
regular-expression  
regular:expression  
regular&expression   

I am provided with the following string which I would need to use the findall() method to match each occurence listed above:

str="This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression"
Carigs
  • 52
  • 7
  • What pattern did not work well? – Wiktor Stribiżew Apr 19 '18 at 18:24
  • 1
    `regular[ :&-]expression` – ctwheels Apr 19 '18 at 18:24
  • Have a look at **character classes**, e.g. `[-:& ]`. – Jan Apr 19 '18 at 18:24
  • See [Including a hyphen in a regex character bracket?](https://stackoverflow.com/questions/3697202/including-a-hyphen-in-a-regex-character-bracket). You might want to have a look at [Learning Regular Expressions](http://stackoverflow.com/a/2759417/3832970). – Wiktor Stribiżew Apr 19 '18 at 18:25
  • Be careful of the dash. In the above example `-` works because it is at the front or back of the set. Otherwise, you need to do `\-` and that may also need a python level escape `\\-` depending on whether you use raw strings. – tdelaney Apr 19 '18 at 18:30

3 Answers3

0
import re
str= (
    'This is a string to search for a regular expression '
    'like regular expression or regular-expression or '
    'regular:expression or regular&expression'
)

r = re.compile(r'regular[- &:]expression')
print(r.findall(str))

Results:

['regular expression', 'regular expression',
'regular-expression', 'regular:expression',
'regular&expression']
nosklo
  • 217,122
  • 57
  • 293
  • 297
0

The correct regular expression will be 'regular[-:&]expression' as seen below

import re
search_string='''This is a string to search for a regular expression like regular 
expression or regular-expression or regular:expression or regular&expression'''

pattern = 'regular[-:&]expression'
match1= re.findall(pattern, search_string)
if match1 != None:
  print(pattern+' matched')
else:
  print(pattern+' did not match')

Output:

 regular[-:&]expression matched 
0

This is done by:

import re
search_string='''This is a string to search for a regular expression like regular 
expression or 
regular-expression or regular:expression or regular&expression'''
results1 = re.sub ("regular[ -:&]expression","regular expression", search_string)
print (results1)
A.Aziz
  • 1
  • 1