2014-02-23 81 views
-2

我希望在我的字符串中找到符号'$'。使用正则表达式匹配

s= 'abc$efg' 
import re 
result = re.match(r'\$',s) 

我想写一个if语句,当$存在时给我一个错误,否则打印OK!

if '$ available in result': 
    print 'error' 
else: 
    print 'OK' 

我想要实现这个使用正则表达式,而不是下面一个简单的方法:

res = str.find('$') 
    if res!=-1: 
    print 'error' 
+1

你有没有试过这个,并且遇到了困难?当更简单的方法可用时,为什么你要为这个问题使用正则表达式? – Krease

+2

只有在字符串的BEGINNING匹配时,'re.match'才会匹配;在你的模式中使用're.search',你就近了。 – dawg

+0

明白了!我知道我可以通过re.search做到这一点。理解re.match会是一个很好的例子吗?如何使用从re.match获得的结果? – NBA

回答

1

要做到这一点,最好的办法是使用in操作:

if '$' in my_string: 
    print('Error') 

使用正则表达式效率更低,速度更慢:

if re.search('\$', my_string): 
    print('Error') 
1

虽然看起来毫无意义的寻找一个更复杂的方式来做到这一点,当你自己已经证明了find方法,并在运营商使用,如:

>>> '$' in s 
True 

会更好过。

re.match只在字符串的最开始处查找匹配项。然而,

你可以试试这个:

s= 'abc$efg' 

import re 

if re.search(r'\$', s): # re.search looks for matches throughout the string 
    print 'error' # raise Error might be more what you want 
else: 
    print 'ok' 
1
import re 

s = 'abc$efg' 

if re.search('\$', s): # Returns true if any instance is found. 
    raise Error 
else: 
    print 'OK' 

我们必须使用转义字符\$因为$re一个特殊字符,但我们只是想找到该字符,而不是用它作为操作数。