2014-12-03 84 views
0

我正在尋找一個正則表達式。正則表達式搜索數字之間的隨機文本

我有一個隨機文本和文本內的是幾個數字與長度9.

實施例:

Test1: "no results!"<br> 
Test2: 123456789 Problems with ...<br> 
Problem xyz -567891234 Problems with ...<br> 
Test4: 987654321 kjdfk sakjsahfkldjasf kj 

我想提取我有這樣的結果的數字:

123456789, 567891234, 987654321 

我可以使用正則表達式查找的數字:

\d{9} 

我的想法是搜索隨機字符,直到找到一個數字,然後將其替換爲「,」。但我無法爲它定義正則表達式。這是我的嘗試:

.*(\d{9}) and then replace with $1 , 

但這並不奏效。有人可以幫我嗎?

+1

什麼是您的實際問題?你有一個正則表達式可以找到合適長度的數字,所以你只需要將它與你選擇的正則表達式庫一起使用來提取匹配。將結果更改爲所需的格式可能比直接在正則表達式中進行後處理更容易 – RobV 2014-12-03 10:57:48

+0

上述輸入的預期輸出是什麼?你正在運行哪種語言? – 2014-12-03 11:00:41

+0

有什麼工具/語言?你是否堅持使用它,或者你是否允許使用其他工具(比如awk,這對於這項任務聽起來很好)? – Tensibai 2014-12-03 11:01:09

回答

0

一個更好的主意是使用你的編程語言的字符串連接方法。例如,在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' 
0
^.*?(\d{9}).*$ 

你可以試試re.sub。看演示。

http://regex101.com/r/yR3mM3/34

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)) 
相關問題