[英]Regex first string between characters
I have this string 我有这串
_text = 'ITEM|6945541514535242|2|'
and how can I retrieve this string '6945541514535242'
with regex? 以及如何使用正则表达式检索此字符串
'6945541514535242'
?
'6945541514535242'
and '2'
are between '|'
'6945541514535242'
和'2'
在'|'
之间 , but I want only get the first one. ,但我只想要第一个。
You can use regex \\|(\\d+)\\|
您可以使用正则表达式
\\|(\\d+)\\|
and re.search
to get only the first match, if any. 和
re.search
如果有只得到了第一场比赛。
>>> _text = 'ITEM|6945541514535242|2|'
>>> re.search(r'\|(\d+)\|', _text).group(1)
'6945541514535242'
If it can be any text you will need to do an 'non-greedy' search: 如果可以是任何文本,则需要进行“非贪婪”搜索:
>>> _text = 'ITEM|abcd6945541514535242|2|'
>>> re.search(r'\|(.*?)\|', _text).group(1)
'abdc6945541514535242'
the ? ? makes it non-greedy so it matches as little as possible
使它变得非贪婪,因此尽可能少地匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.