Python 正则表达式布尔值 'or' 不 select 所有匹配项
Python Regex boolean 'or' doesn't select all matches
我正在尝试匹配一个字符串中的多个子字符串。
感兴趣区域的格式为:
Sample1: "text text text[One]"
Sample2:"text text text[One/Two]"
Sample3:"text text text[One/Two/Three]"
我正在尝试通过以下方式使用正则表达式获取数字列表:
numbers = re.findall('(\[|\/)(\w+)(\/|\])', str)
然而,group2 产生:
#Sample1
['One']
#Sample2
['One']
#Sample3
['One','Three']
无论如何,我无法让它匹配“/”和“]”或“/”之间的第二个数字。但是,我不明白为什么它不匹配“/Two/”,因为“/”字符在两种选择中都是一个选项。
我还尝试使用以下正则表达式以不同的方式构建它:
re.findall('[\[]?[\/]?(\w+)[\/]?[\]]?', str)
虽然它给了我想要的结果,但它也给了我前面文本中的所有单词。
感谢任何建议。
你可以试试这个:
s = ["text text text[One]", "text text text[One/Two]", "text text text[One/Two/Three]"]
import re
final_data = [[b.split('/') for b in re.findall('\[(.*?)\]', i)][0] for i in s]
输出:
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
使用 lookbehind 和 lookahead 所以 [
、/
和 ]
不是匹配的一部分:
>>> [re.findall('(?<=\[|\/)\w+(?=\/|\])', s) for s in samples]
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
这样中间的/
可以用于两场比赛
您也可以试试这个正则表达式:
import re
regex = r"\[.+?\]"
Sample1= "text text text[One]"
Sample2= "text text text[One/Two]"
Sample3= "text text text[One/Two/Three]"
lines=[Sample1,Sample2,Sample3]
subres = [re.findall(r"\[(.+[^\/])\]", s) for s in lines]
result = [res[0].split('/') for res in subres]
print(result)
结果:
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
如果您确定您的目标字符串始终采用您显示的格式,那么为什么不首先找到所有由斜线 分隔的 数字,然后然后在 /
?
上拆分结果
Sample3 = "text text text[One/Two/Three]"
re.findall('\[(.*)\]', Sample3)[0].split('/')
输出:
['One', 'Two', 'Three']
我正在尝试匹配一个字符串中的多个子字符串。
感兴趣区域的格式为:
Sample1: "text text text[One]"
Sample2:"text text text[One/Two]"
Sample3:"text text text[One/Two/Three]"
我正在尝试通过以下方式使用正则表达式获取数字列表:
numbers = re.findall('(\[|\/)(\w+)(\/|\])', str)
然而,group2 产生:
#Sample1
['One']
#Sample2
['One']
#Sample3
['One','Three']
无论如何,我无法让它匹配“/”和“]”或“/”之间的第二个数字。但是,我不明白为什么它不匹配“/Two/”,因为“/”字符在两种选择中都是一个选项。
我还尝试使用以下正则表达式以不同的方式构建它:
re.findall('[\[]?[\/]?(\w+)[\/]?[\]]?', str)
虽然它给了我想要的结果,但它也给了我前面文本中的所有单词。
感谢任何建议。
你可以试试这个:
s = ["text text text[One]", "text text text[One/Two]", "text text text[One/Two/Three]"]
import re
final_data = [[b.split('/') for b in re.findall('\[(.*?)\]', i)][0] for i in s]
输出:
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
使用 lookbehind 和 lookahead 所以 [
、/
和 ]
不是匹配的一部分:
>>> [re.findall('(?<=\[|\/)\w+(?=\/|\])', s) for s in samples]
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
这样中间的/
可以用于两场比赛
您也可以试试这个正则表达式:
import re
regex = r"\[.+?\]"
Sample1= "text text text[One]"
Sample2= "text text text[One/Two]"
Sample3= "text text text[One/Two/Three]"
lines=[Sample1,Sample2,Sample3]
subres = [re.findall(r"\[(.+[^\/])\]", s) for s in lines]
result = [res[0].split('/') for res in subres]
print(result)
结果:
[['One'], ['One', 'Two'], ['One', 'Two', 'Three']]
如果您确定您的目标字符串始终采用您显示的格式,那么为什么不首先找到所有由斜线 分隔的 数字,然后然后在 /
?
Sample3 = "text text text[One/Two/Three]"
re.findall('\[(.*)\]', Sample3)[0].split('/')
输出:
['One', 'Two', 'Three']