Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

python - Do regular expressions from the re module support word boundaries ()?

While trying to learn a little more about regular expressions, a tutorial suggested that you can use the to match a word boundary. However, the following snippet in the Python interpreter does not work as expected:

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

It should have been a match object if anything was matched, but it is None.

Is the expression not supported in Python or am I using it wrong?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why don't you try

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

Output:

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

Also forgot to mention, you should be using raw strings in your code

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...