python - 在考虑带有撇号的单词时,如何在 python 中使用正则表达式分隔单词?

标签 python regex

我尝试使用单词边界在 python 正则表达式中分离 m,并找到它们。这些 m 应该在两边都有一个空格或开始/结束字符串:

r = re.compile("\\bm\\b")
re.findall(r, someString)

但是,由于撇号被认为是单词边界,因此此方法还可以在 I'm 等单词中找到 m。如何编写不将撇号视为单词边界的正则表达式?

我已经试过了:

r = re.compile("(\\sm\\s) | (^m) | (m$)")
re.findall(r, someString)

但这与任何 m 都不匹配。奇怪。

最佳答案

使用环视断言:

>>> import re
>>> re.findall(r'(?<=\s)m(?=\s)|^m|m$', "I'm a boy")
[]
>>> re.findall(r'(?<=\s)m(?=\s)|^m|m$', "I m a boy")
['m']
>>> re.findall(r'(?<=\s)m(?=\s)|^m|m$', "mama")
['m']
>>> re.findall(r'(?<=\s)m(?=\s)|^m|m$', "pm")
['m']

(?=...)

Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef, ...

from Regular expression syntax

顺便说一句,使用原始字符串( r'this is raw string' ),您不需要转义 \ .

>>> r'\s' == '\\s'
True

关于python - 在考虑带有撇号的单词时,如何在 python 中使用正则表达式分隔单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331391/

相关文章:

python - 加权稀疏分类交叉熵

python - 字典列表列表中的调用列表不起作用

python - 使用 cv2.resize 后获取旋转矩形的大小和位置

regex - DFA 到正则表达式的时间复杂度

javascript - 带有 OR 条件的 javascript 中的正则表达式

python - Bottle 网络应用程序不提供静态 css 文件

Python,在处理它们之前删除它们

JavaScript 字符串 : get content of two standing next to each other pieces of content and wrap them together

python - 为什么使用正则表达式 [*?[] 作为 magic_check ?

Java 正则表达式 : Extract multiple sub-strings from a string