正则表达式.如何匹配单词后面没有另一个字符 [英] Regexp. How to match word isn't followed and preceded by another characters
本文介绍了正则表达式.如何匹配单词后面没有另一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将代码中的 mm
单位替换为 cm
单位.在大量此类替换的情况下,我使用 regexp
.
I want to replace mm
units to cm
units in my code. In the case of the big amount of such replacements I use regexp
.
我做了这样的表达:
(?!a-zA-Z)mm(?!a-zA-Z)
但它仍然匹配summa
、gamma
和dummy
之类的词.
But it still matches words like summa
, gamma
and dummy
.
如何正确组成正则表达式?
How to make up regexp correctly?
推荐答案
使用字符类并将第一个 (?!...)
前瞻改为后视:
Use character classes and change the first (?!...)
lookahead into a lookbehind:
(?<![a-zA-Z])mm(?![a-zA-Z])
^^^^^^^^^^^^^ ^^^^^^^^^^^
查看正则表达式演示
模式匹配:
(?<![a-zA-Z])
- 一个否定的 lookbehind,如果有一个紧接在 上的 ASCII 字母,则匹配失败当前位置的左侧mm
- 文字子串(?![a-zA-Z])
- 一个否定的前瞻,如果右边有一个 ASCII 字母,则匹配失败 当前位置
(?<![a-zA-Z])
- a negative lookbehind that fails the match if there is an ASCII letter immediately to the left of the current locationmm
- a literal substring(?![a-zA-Z])
- a negative lookahead that fails the match if there is an ASCII letter immediately to the right of the current location
注意:如果您需要使您的模式识别 Unicode,请将 [a-zA-Z]
替换为 [^\W\d_]
(如果您使用的是 Python 2.x,请使用 re.U
标志).
NOTE: If you need to make your pattern Unicode-aware, replace [a-zA-Z]
with [^\W\d_]
(and use re.U
flag if you are using Python 2.x).
这篇关于正则表达式.如何匹配单词后面没有另一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文