search for strings in python

非 Y 不嫁゛ 提交于 2019-12-25 02:25:56

问题


How could I search for a string in a text and add another string after it like the following:

I want to search for example "John 3 2 G" in a text if it is there I want to add strings after it

I met John 3 2 G yesterday and..

after run the program

I met John 3 2 G and his brother yesterday and..

to be known that the numbers are not fixed, they are numbers but could be changed

I used re.sub but in this case when the numbers are changing how could I do it ?

My attempt:

re.sub("John","John and his brother",text)

回答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.




回答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].




回答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.



来源:https://stackoverflow.com/questions/24392346/search-for-strings-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!