Regex 正则表达式在数字之间搜索随机文本
我在找一个正则表达式 我有一个随机文本,文本中有几个长度为9的数字 例如:Regex 正则表达式在数字之间搜索随机文本,regex,Regex,我在找一个正则表达式 我有一个随机文本,文本中有几个长度为9的数字 例如: Test1: "no results!"<br> Test2: 123456789 Problems with ...<br> Problem xyz -567891234 Problems with ...<br> Test4: 987654321 kjdfk sakjsahfkldjasf kj 我可以找到带有正则表达式的数字: \d{9} 我的想法是搜索随机字符,直到找到一
Test1: "no results!"<br>
Test2: 123456789 Problems with ...<br>
Problem xyz -567891234 Problems with ...<br>
Test4: 987654321 kjdfk sakjsahfkldjasf kj
我可以找到带有正则表达式的数字:
\d{9}
我的想法是搜索随机字符,直到找到一个数字,然后用“,”替换它。但是我不能为它定义正则表达式。这是我的尝试:
.*(\d{9}) and then replace with $1 ,
但这是行不通的。有人能帮我吗?更好的办法是使用编程语言的字符串连接方法。例如,在Python中:
>>> s = """Test1: "no results!"
... Test2: 123456789 Problems with ...
... Problem xyz -567891234 Problems with ...
... Test4: 987654321 kjdfk sakjsahfkldjasf kj"""
>>> ", ".join(re.findall(r"\d{9}", s))
'123456789, 567891234, 987654321'
如果只想使用正则表达式获得相同的结果,则需要分两个步骤来完成,这两个步骤都不是很简单:
>>> temp = re.sub(r"(?s)^.*?(?=\d{9})|(?<=\d{9})(?:(?!\d{9}).)*$", "", s)
>>> temp
'123456789 Problems with ...\nProblem xyz -567891234 Problems with ...\nTest4: 9
87654321'
>>> re.sub(r"(?s)(?!$)(?<=\d{9})(?:(?!\d{9}).)*", ", ", temp)
'123456789, 567891234, 987654321'
temp=re.sub(r“(?s)^.*?(?=\d{9})|(?
您可以使用re.sub
尝试此操作。请参阅演示
您的实际问题是什么?您有一个正则表达式,它可以找到适当长度的数字,因此您只需将它与您选择的正则表达式库一起使用即可提取匹配项。将结果更改为所需格式可能比直接在正则表达式中进行匹配项后处理更容易。您的建议是什么上述输入的预期输出?您运行的是哪种语言?使用的是哪种工具/语言?您是坚持使用它还是允许使用其他工具(如awk,它听起来适合此任务)?
>>> temp = re.sub(r"(?s)^.*?(?=\d{9})|(?<=\d{9})(?:(?!\d{9}).)*$", "", s)
>>> temp
'123456789 Problems with ...\nProblem xyz -567891234 Problems with ...\nTest4: 9
87654321'
>>> re.sub(r"(?s)(?!$)(?<=\d{9})(?:(?!\d{9}).)*", ", ", temp)
'123456789, 567891234, 987654321'
^.*?(\d{9}).*$
import re
ll=[]
p = re.compile(r'^(?:.*?(\d{9}))+.*$', re.Multiline)
subst = "\1"
for line in test_data:
ll.append(re.sub(p, subst, line))