【问题标题】:Python Regular Expression and MetacharactersPython 正则表达式和元字符
【发布时间】:2017-03-12 19:55:45
【问题描述】:

有一个变量是:

line="s(a)='asd'"

我正在尝试查找包含“s()”的部分。

我尝试使用:

re.match("s(*)",line)

但似乎无法搜索包含 ( )

的字符

有没有办法在python中找到并打印出来?

【问题讨论】:

标签: python regex metacharacters


【解决方案1】:

你的正则表达式是这里的问题。

你可以使用:

>>> line="s(a)='asd'"
>>> print re.findall(r's\([^)]*\)', line)
['s(a)']

RegEx 拆分:

s     # match letter s
\(    # match literal (
[^)]* # Using a negated character class, match 0 more of any char that is not )
\)    $ match literal (
  • r 用于 Python 中的原始字符串。

【讨论】:

  • 感谢您的快速回复!
  • 您可能还应该提到r'...' 字符串的好处。 (虽然在这个例子中,它并没有真正的区别。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
  • 2016-07-05
  • 2015-12-28
  • 2020-07-24
相关资源
最近更新 更多