对于输入字符串,想要匹配以开头{(P)
和结尾的文本(P)}
,而我只想匹配中间的部分。想知道我们是否可以编写一个正则表达式来解决此问题?
例如,在下面的示例中,对于输入字符串,我想检索hello world部分。使用Python 2.7。
python {(P)hello world(P)} java
您可以尝试{\(P\)(.*)\(P\)}
使用模式中的括号来捕获{(P)
和之间的所有内容(P)}
:
import re
re.findall(r'{\(P\)(.*)\(P\)}', "python {(P)hello world(P)} java")
# ['hello world']
.*
还匹配unicode字符,例如:
import re
str1 = "python {(P)£1,073,142.68(P)} java"
str2 = re.findall(r'{\(P\)(.*)\(P\)}', str1)[0]
str2
# '\xc2\xa31,073,142.68'
print str2
# £1,073,142.68
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句