使用正则表达式匹配

时间:2014-02-23 23:34:43

标签: python

我希望在我的字符串中找到符号'$'。

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'

3 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是使用in运算符:

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

使用正则表达式的效率和速度都低得多:

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

答案 1 :(得分:1)

虽然寻找一种更复杂的方法来实现这一点似乎毫无意义,但当你自己演示了find方法并使用in运算符时,如:

>>> '$' 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'

答案 2 :(得分:1)

import re

s = 'abc$efg'

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

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

相关问题