[英]Extracting text between curly braces in python
我有一串如下的文字
1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 )
我想在上面的字符串中提取abc
和memo
。 我正則表達式為[鏈接如下這里]基本{(?:[^{}])*}
但它抓住一切(returns abc, cde, memo, bleh)
我會保持簡單。
import re
s = '1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 )'
s_without_parens = re.sub('\(.+?\)','',s)
text_in_brackets = re.findall('{(.+?)}',s_without_parens)
text_in_brackets
[' abc ', ' memo ']
因此,您可以將其嵌套為re.findall('{(.+?)}',re.sub('\\(.+?\\)','',s))
,但是我發現將其分解為邏輯步驟。
你可以做:
\d+\.[^{]*{\s+([^}]+)\s+}
並獲取捕獲的組。
\\d+\\.
匹配一個或多個數字,后跟一個.
[^{]*
匹配到下一個{
, {\\s+
匹配{
,后跟一個或多個空格
捕獲的組([^}]+)
匹配到下一個}
\\s+}
匹配一個或多個空格,后跟}
例:
In [48]: blob = '1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 )'
In [49]: re.findall(r'\d+\.[^{]*{\s+([^}]+)\s+}', blob)
Out[49]: ['abc', 'memo']
簡單的re.findall()
方法:
import re
s = '1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 )'
result = re.findall(r'\{ ([^{}]+) \} (?=\()', s)
print(result)
輸出:
['abc', 'memo']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.