简体   繁体   English

如何搜索字符串的所有出现的 substring 并将该 substring 旁边的 valuenext 存储到 python 中的变量中?

[英]How I search all the occurrence of a substring of a string and store the valuenext to that substring to a variable in python?

string s1 = "abc:12 Hellow world abc:342 hi there abc:15 Here,in python,I want to search all 'abc' and store the value after semicolon. To be more specific,if I search 'abc' substring,then 12;342;15 value would be stored in variable. string s1 = "abc:12 Hellow world abc:342 hi there abc:15在这里,在 python 中,我想搜索所有'abc'并存储分号后的值。更具体地说,如果我搜索'abc' substring,然后12;342;15值将存储在变量中。

this regex finds all abc<optional whitespaces>:<optional whitespace><value> where <value> must not contain whitespace characters or quotes...此正则表达式查找所有abc<optional whitespaces>:<optional whitespace><value>其中<value>不得包含空格字符或引号...

import re
data = """
string s1 = "abc:12 Hellow world abc :342 hi there abc :15"
"""

l = re.findall(r'abc\s*:\s*([^\s\"\']+)', data)
print(l)

l is your list of values and holds ['12', '342', '15'] l是您的值列表并保存['12', '342', '15']

according to your specification, this is not restricted to numerical values (you might want to adapt the regex if your values can only be integer numbers)根据您的规范,这不仅限于数值(如果您的值只能是 integer 数字,您可能需要调整正则表达式)

You can use regular expressions:您可以使用正则表达式:

import re

string = "abc:12 Hellow world abc :342 hi there abc :15"
pattern = re.compile(r"abc.*?:(.+?)\b")
matches = pattern.findall(string)

print(matches) # ['12', '342', '15']

Demo: https://regex101.com/r/gAQwVs/1演示: https://regex101.com/r/gAQwVs/1

Try this尝试这个

Based on you'r input!根据您的输入!

 a = [int(x.split(" ")[0][1:]) for x in s1.split("abc")[1:]]
 print(a)

Output Output

 [12, 342, 15]
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中搜索字符串中是否出现子字符串(包括部分匹配项)? - How can I search a string for any occurrence of substring (including partial matches) in python? Python正则表达式在多行字符串变量中搜索子字符串 - Python regex to search substring in multiline string variable 如何在Python的字符串中搜索带引号的子字符串? - How do I search for a substring with a quotation mark inside a string in Python? 如何搜索介于 python 中字符串的两个值之间的 substring? - How can I search for a substring that is between two values ​of a string in python? 替换除 Python 中第一次出现的 substring 之外的所有内容? - Replace all except the first occurrence of a substring in Python? 在 Python 中查找字符串中的所有子字符串,我怎样才能使它更好? - Find all substring in a string in Python, how can I make it better? 如何在python中搜索子字符串? - How to search substring in python? 如何在python中查找字符串中所有出现的子字符串 - How to find all occurences of substring in string, in python 如何找到python中另一个子字符串后出现的第一个子字符串? - How can I find the first occurrence of a substring occurring after another substring in python? 如何在最后一次出现子字符串之前获取字符串? - How to get String Before Last occurrence of substring?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM