[英]python Regex to find values between 2 strings
I have a string: a = '*1357*0123456789012345678901234567890123456789*2468*'
我有一个字符串:
a = '*1357*0123456789012345678901234567890123456789*2468*'
I want to find a value between 1357
and 2468
which is 0123456789012345678901234567890123456789
. 我想在
1357
和2468
之间找到一个值为0123456789012345678901234567890123456789
。
I want to use regex or easier method to extract the value. 我想使用正则表达式或更简单的方法来提取值。
I tried re.findall(r'1357\\.(.*?)2468', a)
, but I don't know where I'm doing wrong. 我尝试了
re.findall(r'1357\\.(.*?)2468', a)
,但是我不知道我在哪里做错了。
You have a couple of problems here: 您在这里有几个问题:
.
.
after 1357
, which means a literal .
1357
年后,意思是文字.
, which isn't what you meant to have *
characters (which do need to be escaped, of course). *
字符(这确实需要进行转义,当然)。 To make a long story short: 使长话短说:
re.findall(r'1357\*(.*?)\*2468', a)
If you want a slightly more general or flexible method, you can use this: 如果您想要一种更通用或更灵活的方法,可以使用以下方法:
re.findall(r'\*\d+\*(\d+)\*\d+\*',a)
Which gives you the same output: 这将为您提供相同的输出:
['0123456789012345678901234567890123456789']
But the advantage is that it gives you the value between any set of numeric values that are surrounded by the *
. 但是这样做的好处是,它可以为您提供由
*
包围的任何一组数字值之间的值。 For instance, this would work for your string, but also for the string a = *0101*0123456789012345678901234567890123456789*0*
, etc... 例如,这将适用于您的字符串,但也适用于字符串
a = *0101*0123456789012345678901234567890123456789*0*
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.