从单个符号到任何字母数字符号或 EOL 的 Python 正则表达式

Python regex from single symbol to any alphanumeric symbols or EOL

提问人:Dmitrii 提问时间:10/14/2023 更新时间:10/14/2023 访问量:54

问:

import re
text123 = "test, test12, #test3,  #test4 - : test555"
print(re.findall(r"#.*[^a-zA-Z\d\s:]",  text123)) 
# expected ['#test3', '#test4']
# result ['#test3,  #test4 -']

print(re.findall(r"#.*[^a-zA-Z\d]",  text123)) 
# expected ['#test3', '#test4']
# result ['#test3,  #test4 - : ']est3,  #test4 - ']

print(re.findall(r"#.*?[^a-zA-Z\d]",  text123)) 
# result ['#test3,', '#test4 ']
# what would I like- ['#test3', '#test4']

我尝试查找所有以特定字符开头和结尾的子字符串 找到所有以特定字符开头和结尾的子字符串

和其他链接\手册\等 - 没办法

Python 正则表达式 拆分

评论

0赞 Barmar 10/14/2023
使用非贪婪.*?
0赞 Barmar 10/14/2023
或更改为.*[a-zA-Z\d\s:]*
0赞 Cary Swoveland 10/14/2023
你没有准确和明确地陈述这个问题。如果是,“匹配所有仅包含字母和数字的字符串,这些字符串以字母开头,以数字结尾,没有字母前面有数字”,则匹配 。[a-zA-Z]+\d+

答:

0赞 Denys Horobchenko 10/14/2023 #1

如果您尝试查找字母数字,为什么不使用字母数字而不是点符号?放你想要的,避免你不想要的。

import re
text123 = "test, test12, #test3,  #test4 - : test555"
print(re.findall(r"#[a-zA-Z\d]+",  text123)) 
# expected ['#test3', '#test4']
# result ['#test3,  #test4']

评论

0赞 Dmitrii 10/14/2023
对于西里尔文 - text124 = “мама мыла раму #рама #mama8 #прочее” print(re.findall(r“#[a-zA-Z0-9А-Яa-я]+”, text124))
0赞 Denys Horobchenko 10/14/2023
这超出了问题的范围。您仍然可以在这里找到答案,例如 stackoverflow.com/questions/15448274/...stackoverflow.com/questions/7206499/......