import regex
text = ["text 123 ->My Mom's house<- jidjio",
"bla bla ->My8Mo2ms231#43house<- bla bla",
"Test string ->My Mom's' house<- further text",
"wkashhasMdykMomLsfheoousssswQseBswenksd",
"textMy?M?om*s?*hou?*seorsomethingelse",
"thisIs3MôyMäoméshouseEFSAcasw!"]
search_string = "MyMomshouse"
regex_string = r'.*?'.join(str(c) for c in search_string)
regex_string2 = r'[^a-zA-Z]*?'.join(str(c) for c in search_string)
regex_string3 = r'\P{L}*?'.join(str(c) for c in search_string)
print('\n - regex 1 -')
for t in text:
print(regex.search(regex_string, t))
print('\n - regex 2 -')
for t in text:
print(regex.search(regex_string2, t))
print('\n - regex 3 -')
for t in text:
print(regex.search(regex_string3, t))
匹配
所以,从你的问题来看,我相信你在寻找这个
或
第一个匹配搜索字符串加上搜索字符串字符之间的任何字符(如问题正文中所述,请参见regex101),第二个匹配非字母字符(如问题标题所示,请参见regex101)
其中每一个都是从搜索字符串的字符构建的,其模式是惰性地匹配任何字符(案例1)或任何非字母字符(案例2)
注意:如果您希望第二个也排除“特殊”字字符,例如
é
、ü
或ô
,则需要在您使用的正则表达式模式中相应地处理它们,例如通过使用unicode类别\P{L}
\p{L}
匹配类别“字母”中的单个代码点,\P{L}
匹配相反的代码点(请参见regex101)构建表达式
无论您的确切表达式是什么,您都可以通过将搜索字符串的每个字符与您选择的表达式相连接来轻松构建最终的正则表达式字符串
Python示例
下面是一个python示例(因为您的问题没有使用编程语言标记):
输出:
注:
regex
模块而不是re
模块,因为它支持\p{L}
模式李>'.*?'.join(regex.escape(str(c)) for c in search_string)
MyMomshouse
(无空格),而不是您指定的字符串,因为您的字符串与示例字符串中的第二个字符串不匹配李>JavaScript示例:
在JavaScript中,或者在原则上,在任何语言中,都可以做到这一点。另见this JS fiddle:
但是,unicode字符组支持并不总是可用的,请参见this SO questions and its answers for possible solutions
相关问题 更多 >
编程相关推荐