python 正则表达式的使用

python正则表达式的使用


使用re模块实现正则表达式
使用re.search(regex,string)方法检出string字符串是否匹配正则表达式regex,如果匹配到就会返回一个match对象,否则返回None

符号 作用
. 匹配任意一个字符
^ 匹配任意开始的字符串
$ 匹配任意结束的字符串
[] 匹配多个字符 如:"[bcr]at"代表的是匹配“bat”“cat”以及"rat"
{} 表示匹配的长度
import re
text_string = '我喜欢爬虫。你呢。我不喜欢它。虽然爬虫很有用。但是我学不会它呢。我喜欢爬山。'
regex = '爬虫'
p_string = text_string.split('。')
for line in p_string:
    if re.search(regex,line):
        print(line)
我喜欢爬虫
虽然爬虫很有用
regex = '爬.'
p_string = text_string.split('。')
for line in p_string:
    if re.search(regex,line):
        print(line)
我喜欢爬虫
虽然爬虫很有用
我喜欢爬山
regex = '呢$'
p_string = text_string.split('。')
for line in p_string:
    if re.search(regex,line):
        print(line)
你呢
但是我学不会它呢
text_string = ['[重要的]今年第七号台风23日登陆','上海是座美丽的城市','[紧要的]中国对印度连发强硬警告']
regex = '^\[[重紧]..\]'
for line in text_string:
    if re.search(regex,line):
        print(line)
    else:
        print("not match")
[重要的]今年第七号台风23日登陆
not match
[紧要的]中国对印度连发强硬警告

抽取所有年份

strings = ['war of 1812', 'There are 5280 feet to a mile','Happy New Year 2016!']
year_strings = []
for str in strings:
    # 字符串有英文有数字,匹配其中数字部分,并且是在1000~2999之间
    # {3}代表的是重复之前的[0-9]三次,是[0-9][0-9][0-9]的简化写法
    if re.search('[1-2][0-9]{3}',str):
        year_strings.append(str)
print(year_strings)
['war of 1812', 'Happy New Year 2016!']
year_string = '2016 was a good year,but 2017 will be better!'
years = re.findall('[2][0-9]{3}',year_string)
print(years)
['2016', '2017']

你可能感兴趣的:(python,正则表达式,爬虫)