[Python]几个正则表达式匹配的例子
2014-07-26 22:45
691 查看
例一、匹配以abc开头的单词。
['abcthis']
例二、匹配不是以abc开头的单词。
['is', 'thatabc', 'colvin']
['is', 'thatabc', 'colvin']
['is', 'colvin']
['is', 'thatabc', 'colvin']
例三、匹配不包含abc的单词。
[('is', 's'), ('colvin', 'n')]
例四、对字符串中的数值每3位添加一个小数点:
13324323 => 13.324.323
This is 1965th => This is 1965th
333 => 333
435.453.454.534
text = "abcthis is thatabc colvin" pat = r"\b(?=abc)\w*" print re.findall(pat,text)>>>
['abcthis']
例二、匹配不是以abc开头的单词。
text = "abcthis is thatabc colvin" pat2 = r"\b(?!abc)\w+" print re.findall(pat2,text)>>>
['is', 'thatabc', 'colvin']
text = "abcthis is thatabc colvin" pat3 = r"(?<!\w)(?=\w)(?!abc)\w+" print re.findall(pat3,text)>>>
['is', 'thatabc', 'colvin']
print re.findall(r"\b[^\Wa][^\Wb]?[^\Wc]?\w*\b","abcthis is abcthat colvin")>>>
['is', 'colvin']
def getpat(str): pat = r"".join(["[^\W"+y+"]"+"?"*(x>0) for x,y in enumerate(str)]) pat = r"\b"+pat+r"\w*\b" return pat pat = getpat("abc") print re.findall(pat,text)>>>
['is', 'thatabc', 'colvin']
例三、匹配不包含abc的单词。
text = "abcthis is thatabc colvin" pat4 = r"\b(((?!abc)\w)+)\b" print re.findall(pat4,text)>>>
[('is', 's'), ('colvin', 'n')]
例四、对字符串中的数值每3位添加一个小数点:
13324323 => 13.324.323
This is 1965th => This is 1965th
333 => 333
print re.sub(r'(?<=\d)(?=(\d\d\d)+\b)', '.', str('435453454534'))>>>
435.453.454.534
相关文章推荐
- python正则表达式几个例子
- (学习)python非贪婪、多行匹配正则表达式例子
- (学习)python非贪婪、多行匹配正则表达式例子 分类: 正则表达式 2013-08-19 11:21 2540人阅读 评论(2) 收藏
- python非贪婪、多行匹配正则表达式例子[转载]
- (学习)python非贪婪、多行匹配正则表达式例子
- python非贪婪、多行匹配正则表达式例子
- Python中的正则表达式匹配中文问题
- Python中正则表达式对中文的匹配问题
- 转载:Python正则表达式的用法(1. 匹配)
- Python:正则表达式匹配任意字符(包括换行符)的写法
- 正则表达式(四) 部分例子,匹配规则
- 比较常用的几个正则表达式(匹配数字)
- Python 正则表达式(模式匹配)
- Python正则表达式的几种匹配用法
- 用python做含有中文的正则表达式模式匹配
- python正则表达式匹配sql语句中的表名
- [转]Python正则表达式中匹配GBK/UTF-8编码中文字符_绝冬之地_百度空间
- Python 匹配任意字符(包括换行符)的正则表达式写法
- js正则表达式的几个匹配方法
- python类库31[正则表达式匹配实例]