正则表达式匹配某些字符

时间:2015-12-03 14:12:08

标签: python regex string

我有这样的字符串...

"1. yada yada yada (This is a string; "This is a thing")
 2. blah blah blah (This is also a string)"

我想回来......

['this is a string', 'this is also a string']

所以它应匹配'('和&#39 ;;'或'('和')'之间的所有内容。

这是我到目前为止在python中匹配我想要的部分,但我无法弄清楚如何将它们剪下来以返回我真正想要的内容...

pattern = re.compile('\([a-zAZ ;"]+\)|\([a-zAZ ]+\)')
re.findall(pattern)

它返回此...

['(This is a string; "This is a thing"), '(This is also a string)']

编辑增加更多信息:

我意识到我想省略的数字文本部分上面有更多的括号....

"some text and stuff (some more info)
 1. yada yada yada (This is a string; "This is a thing")
 2. blah blah blah (This is also a string)"

我不想匹配"(更多信息)"但我不确定如何只在数字后面加上文字(例如1. lskdfjlsdjfds(我想要的字符串))

2 个答案:

答案 0 :(得分:2)

您可以使用

\(([^);]+)

regex demo is available here

请注意我在非转义括号的帮助下设置的捕获组:使用此子模式捕获的值由re.findall method返回,而不是整个匹配。

匹配

  • \( - 文字(
  • ([^);]+) - 匹配并捕获);
  • 以外的1个或多个字符

Python demo

import re
p = re.compile(r'\(([^);]+)')
test_str = "1. yada yada yada (This is a string; \"This is a thing\")\n2. blah blah blah (This is also a string)"
print(p.findall(test_str)) # => ['This is a string', 'This is also a string']

答案 1 :(得分:1)

我建议

# ^         - start of string
# [^\(]*    - everything that's not an opening bracket
# \(        - opening bracket
# ([^;\)]+) - capture everything that's not semicolon or closing bracket

将其拆分为部分:

pattern = re.compile(r'^[^\(]*\(([^;\)]+)', re.MULTILINE)
matches = pattern.findall(string_to_search)

除非你当然希望对“blah blah blah”部分强加(或放弃)一些要求。

你可以放弃前两个部分,但它会匹配一些它可能不应该的东西......或者它可能应该。这一切都取决于你的目标是什么。

P上。 S.错过了你想要找到所有实例。因此需要设置多行标志:

"""1. yada yada yada (This is a string; "This is a (thing)")
2. blah blah blah (This is also a string)"""

检查行的开头很重要,因为您的输入可以是:

easyXDM.js