Вопрос-Ответ

Do regular expressions from the re module support word boundaries (\b)?

Поддерживают ли регулярные выражения из модуля re границы слов ()?

При попытке узнать немного больше о регулярных выражениях в руководстве было предложено использовать \b для сопоставления границ слов. Однако следующий фрагмент в интерпретаторе Python работает не так, как ожидалось:

>>> x = 'one two three'
>>> y = re.search("\btwo\b", x)

Это должен был быть объект сопоставления, если что-либо было сопоставлено, но это так None.

\b Выражение не поддерживается в Python или я использую его неправильно?

Переведено автоматически
Ответ 1

Вы должны использовать необработанные строки в своем коде

>>> x = 'one two three'
>>> y = re.search(r"\btwo\b", x)
>>> y
<_sre.SRE_Match object at 0x100418a58>
>>>

Кроме того, почему бы вам не попробовать

word = 'two'
re.compile(r'\b%s\b' % word, re.I)

Вывод:

>>> word = 'two'
>>> k = re.compile(r'\b%s\b' % word, re.I)
>>> x = 'one two three'
>>> y = k.search( x)
>>> y
<_sre.SRE_Match object at 0x100418850>
Ответ 2

Это сработает: re.search(r"\btwo\b", x)

Когда вы пишете "\b" на Python, это один символ: "\x08". Либо экранируйте обратную косую черту следующим образом:

"\\b"

или напишите необработанную строку, подобную этой:

r"\b"
Ответ 3

Just to explicitly explain why re.search("\btwo\b", x) doesn't work, it's because \b in a Python string is shorthand for a backspace character.

print("foo\bbar")
fobar

So the pattern "\btwo\b" is looking for a backspace, followed by two, followed by another backspace, which the string you're searching in (x = 'one two three') doesn't have.

To allow re.search (or compile) to interpret the sequence \b as a word boundary, either escape the backslashes ("\\btwo\\b") or use a raw string to create your pattern (r"\btwo\b").

Ответ 4

Python documentation

https://docs.python.org/2/library/re.html#regular-expression-syntax


\b


Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. For example, r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.


2023-10-13 04:45 python regex