如何在使用正则表达式标记化包含括号的同时查找括号之间的文本
How do I find text between brackets while including the bracket using regex tokenization
如何使用正则表达式提取括号内的文本?
例如,如果我有
字符串='This is a test code [asdf -wer -a2 asdf] (ascd asdfas -were)'
我希望输出为
[asdf-wer-a2-asdf], (ascd asdfas -were)
这个问题我到处找了,也没能解决这个问题。
如果有人能帮助我那就太好了
谢谢
这可能不是最好的解决方案,但非常简洁。您指定查找分隔符之间的文本。我提供了开始 [
和结束 ]
,最后是卷曲的 (
和 )
。
s = 'This is a test code [asdf -wer -a2 asdf] (ascd asdfas -were)'
print (s[s.find("[")+1:s.find("]")])
print (s[s.find("(")+1:s.find(")")])
编辑:如果你想要 [] 和 (),只需这样做:
print (s[s.find("["):s.find("]")+1])
print (s[s.find("("):s.find(")")+1])
Returns:
[asdf -wer -a2 asdf]
(ascd asdfas -were)
st = 'This is a test code [asdf -wer -a2 asdf] (ascd asdfas -were)'
import re
mo = re.search(r'(\[.+\])\s*(\(.+\))',st)
print(mo.groups(2)[0],mo.groups(2)[1])
[asdf -wer -a2 asdf] (ascd asdfas -were)
您可以使用以下正则表达式模式。 Here是一个例子
\[[^\)]*\]|\([^)]*\)
如何使用正则表达式提取括号内的文本? 例如,如果我有
字符串='This is a test code [asdf -wer -a2 asdf] (ascd asdfas -were)'
我希望输出为
[asdf-wer-a2-asdf], (ascd asdfas -were)
这个问题我到处找了,也没能解决这个问题。 如果有人能帮助我那就太好了
谢谢
这可能不是最好的解决方案,但非常简洁。您指定查找分隔符之间的文本。我提供了开始 [
和结束 ]
,最后是卷曲的 (
和 )
。
s = 'This is a test code [asdf -wer -a2 asdf] (ascd asdfas -were)'
print (s[s.find("[")+1:s.find("]")])
print (s[s.find("(")+1:s.find(")")])
编辑:如果你想要 [] 和 (),只需这样做:
print (s[s.find("["):s.find("]")+1])
print (s[s.find("("):s.find(")")+1])
Returns:
[asdf -wer -a2 asdf] (ascd asdfas -were)
st = 'This is a test code [asdf -wer -a2 asdf] (ascd asdfas -were)'
import re
mo = re.search(r'(\[.+\])\s*(\(.+\))',st)
print(mo.groups(2)[0],mo.groups(2)[1])
[asdf -wer -a2 asdf] (ascd asdfas -were)
您可以使用以下正则表达式模式。 Here是一个例子
\[[^\)]*\]|\([^)]*\)