简体   繁体   English

正则表达式字符之间的第一个字符串

[英]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.

相关问题 检查字符串是否匹配正则表达式的前 n 个字符 - check if string matches first n characters of regex Python 正则表达式,否定字符串之间的一组字符 - Python regex, negate a set of characters in between a string 使用Python正则表达式在字符之间拆分字符串 - Split string between characters with Python regex 正则表达式:介于常量和可变字符之间的字符串 - Regex: string between a mix of constant and variable characters 如何在 python 中使用正则表达式跳过字符串中 2 个字符之间的字符? - how to skip the characters between 2 characters in a string using regex in python? 正则表达式 - 字符串和第一次出现之间的Python匹配 - Regex - Python matching between string and first occurence 正则表达式以匹配特殊字符之间的第一和第三组数字 - Regex to match first and third groups of numbers between special characters 如何在python中使用正则表达式获取两个特定字符之间的第一个整数? - How to get first integer between two specific characters with regex in Python? Python:如何使用正则表达式替换字符串中不需要的字符的第一个实例 - Python: How to replace the first instance of unwanted characters in a string using regex 如何使用正则表达式从字符串中提取前两个字符 - How to extract first two characters from string using regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM