正则表达式(一) search

何为正则表达式?

正则表达式,又称规则表达式,英文名为RegularExpression,在代码中常简写为regex、regexp或RE,是计算机科学的一个概念。正则表通常被用来检索、替换那些符合某个模式(Patterns)的文本。

正则表达式是对字符串(包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”))操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。正则表达式是一种文本模式,模式描述在搜索文本时要匹配的一个或多个字符串。

Find Patterns in Text(文本查找模式)

关于re的最常见用法是在文本中搜索模式

常用re.search()

string进行搜索,成功返回Match object, 失败返回None, 只匹配一个

search(pattern, string, flags=0):

"""Scan through string looking for a match to the pattern, returning

a match object, or None if no match was found."""


例子1:

import re

patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'

for pattern in patterns:
    print 'Looking for "%s" in "%s" ->' % (pattern, text),

    if re.search(pattern,  text):
        print 'found a match!'
    else:
        print 'no match'

       例子2:

import re

pattern='this' #AB
text='Does this text match the pattern ?'

match=re.search(pattern,text)

if match:   
    s = match.start()
    e = match.end()
    print('Found "%s" in "%s" from %d to %d("%s")' % \
          (pattern,text, s, e, text[s:e]))
else:
    print('No found')

参考:

[1]https://baike.sogou.com/v107588.htm?fromTitle=正则表达式

[2]https://pymotw.com/2/re/#finding-patterns-in-text



猜你喜欢

转载自blog.csdn.net/u010009033/article/details/80658441