Search For Strings In Python
Solution 1:
You can use regular expression pattern matching to tell Python to Match "'John', followed by a space, followed by a digit, followed by a space, followed by a digit, followed by a capital letter".
>>> re.sub(r"John\s(\d\s\d\s[A-Z])", r"John \1 and his brother", a)
'I met John 3 2 G and his brother yesterday'
\s
= whitespace
\d
= digit
[A-Z]
= Captial letter between A and Z.
The parenthesis around \d\s\d\s[A-Z]
tells Python to "capture" that part of the matched pattern, allowing us to access it in the replacement string using \1
.
Solution 2:
Since you know that they'll be numbers but you don't know for sure what the numbers will be, you could use
text = re.sub(r'(\w+ \d+ \d+ \w+)',r'\1 and his brother',text)
That should replace "I met <word> <number> <number> <word> yesterday and..."
where John and G can be anything so long as they appear in that order with two numbers between.
If you need it to replace specifically a single capital letter in the fourth spot, you can change the \w+
to [A-Z]
.
Solution 3:
You could try the below regex which uses positive lookahead,
>>>import re>>>str = 'I met John 3 2 G yesterday and..'>>>m = re.sub(r'(John.*)(?=yesterday)', r'\1and his brother ', str)>>>m
'I met John 3 2 G and his brother yesterday and..'
Explanation:
(John.*)(?=yesterday)
Matches all the characters which are followed by the string John(including John) upto the string yesterday and stored it into a group.In the replacement part we again call the stored group through backreference.
Post a Comment for "Search For Strings In Python"