【问题标题】:python regex matching between two wild characters两个通配符之间的python正则表达式匹配
【发布时间】:2019-03-13 01:13:48
【问题描述】:

我有一个文件,其中包含以下格式的一些行。

...
...
ABC_DEF( ac, bad, dd, ..)
...
...

我想从 ABC_DEF 中获取 ac 和 bad 并修改文件,这样 ..

...
...
ac, bad, 
ABC_DEF(dd, ...)
...
...

ac 和 bad 只是示例,它将是具有一定大小的字母数字字符。

我在python中有以下代码

import re
for line in fileinput.input(inplace=1):
    line = re.sub(r'ABC_DEF\(\w+,\w+,', r'ABC_DEF(', line.rstrip())
    print(line)

但这似乎不起作用。有人可以帮忙吗?

谢谢,

【问题讨论】:

  • re.sub(r'ABC_DEF(\s*\w+\s*,\s*\w+\s*,\s*', r'ABC_DEF(', line.rstrip() ) 似乎工作正常。我想抓住 ac 和 bad 并将这两个词放在上面的文件行中。

标签: python regex file


【解决方案1】:

我认为你需要

line = re.sub(r'ABC_DEF\(\s*\w+\s*,\s*\w+\s*,\s*', r'ABC_DEF(', line.rstrip())

因为单词周围可能有空格。

>>> line = 'ABC_DEF(  first ,  second   , third, fourth)'
>>> line = re.sub(r'ABC_DEF\(\s*\w+\s*,\s*\w+\s*,\s*', 
r'ABC_DEF(', line.rstrip())
>>> line
'ABC_DEF(third, fourth)'

更新:您在 cmets 中询问您想知道如何捕获这些值。为此,您可以将括号放在要捕获的部分上,然后改为调用 re.match。像这样:

>>> line = 'ABC_DEF(  first ,  second   , third, fourth)'
>>> match = re.match(r'ABC_DEF\(\s*(\w+)\s*,\s*(\w+)\s*,\s*', line)
>>> match.group(1)
'first'
>>> match.group(2)
'second'

【讨论】:

  • 谢谢雷.. 对不起。我无法投票或将其标记为正确答案。我是新手。
  • 我还有一个疑问 .. 是否可以将其捕获并存储在一些变量中 .. 例如 $1 = first 和 $2=second。 ..
  • 添加到答案中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 2016-09-02
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
相关资源
最近更新 更多