2017-10-13 25 views
1

我寫一個正則表達式表達式提取的符號(#/ - ),接着是word.For例如,考慮串正則表達式中提取多個符號,隨後字在字符串-python

s= "the amount is 5/10 of the original. The #2 number should be extracted on the dd/yy" 

表達正則表達式是

r= re.search(r'(/|#).*\\s+',s) 

其中我得到用於上述的輸出是無在哪裏,因爲我預期它顯示

/10 #2 /yy 

我的正則表達式有什麼問題。

+0

首先,你的正則表達式是錯誤的;其次,如果沒有發現匹配,如果發現匹配的正則表達式對象re.search返回無。改用re.findall()。 –

+0

@BhawandeepSingla:我知道我的正則表達式有問題。這是它返回None。由於我不確定有什麼問題,我正在尋求幫助,以便有人能夠指出我的錯誤來幫助我。 – shan

回答

2

你需要/#(可與[/#]字符類進行匹配)後,以匹配任何1+非空白字符(含\S+):

[/#]\S+ 

regex demo

提示:如果你不想在一開始的#/與任何單詞字符前面做,在模式開始在前面加上\B(非單詞邊界):\B[/#]\S+

使用re.findall在Python:

import re 
s= "the amount is 5/10 of the original. The #2 number should be extracted on the dd/yy" 
r = re.findall(r'[/#]\S+',s) 
print(r)    # => ['/10', '#2', '/yy'] 
print(" ".join(r)) # => /10 #2 /yy 

Python demo

1
import re 
s = "the amount is 5/10 of the original. The #2 number should be extracted on the dd/yy" 
r = re.findall(r'([/#]\S*)+', s) 
print r 
# ['/10', '#2', '/yy'] 

正則表達式demo

什麼是錯誤的,我正則表達式。

  • ()表示捕獲組。使用[]的字符集
  • \\s匹配意味着匹配字符串\s
+0

這將匹配'/'和'#',這不是OP想要的。你不需要在課堂上逃避'/'。我建議你完全拷貝Wiktor的答案*。 ;-) –

1

至於你說:

提取符號(#/ - )followed by a word

所以你可以使用負面展望。

import re 

pattern=r'/(?!/w).+?[^\s]|#\d' 

strings= "the amount is 5/10 of the original. The #2 number should be extracted on the dd/yy" 

match=re.findall(pattern,strings,re.M) 

print(" ".join(list(match))) 

輸出:

/10 #2 /yy