2017-10-13 88 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 
相关问题