re 模块中的正则表达式是否支持单词边界 ()? [英] Do regular expressions from the re module support word boundaries ()?

查看:36
本文介绍了re 模块中的正则表达式是否支持单词边界 ()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试学习更多有关正则表达式的知识时,一个教程建议您可以使用  来匹配单词边界.但是,Python 解释器中的以下代码段无法按预期工作:

<预><代码>>>>x = '一二三'>>>y = re.search("two", x)

如果有任何匹配,它应该是一个匹配对象,但它是None.

Python 不支持  表达式还是我使用错误?

解决方案

应该在您的代码中使用原始字符串

<预><代码>>>>x = '一二三'>>>y = re.search(r"two", x)>>>是<_sre.SRE_Match 对象在 0x100418a58>>>>

另外,你为什么不试试

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

输出:

<预><代码>>>>字 = '二'>>>k = re.compile(r'%s' % word, re.I)>>>x = '一二三'>>>y = k.search( x)>>>是<_sre.SRE_Match 对象在 0x100418850>

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?

解决方案

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>
>>> 

Also, 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>

这篇关于re 模块中的正则表达式是否支持单词边界 ()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆