[英]How can I search a string for any occurrence of substring (including partial matches) in 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
在這里,在 python 中,我想搜索所有'abc'
並存儲分號后的值。更具體地說,如果我搜索'abc'
substring,然后12;342;15
值將存儲在變量中。
此正則表達式查找所有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
是您的值列表並保存['12', '342', '15']
根據您的規范,這不僅限於數值(如果您的值只能是 integer 數字,您可能需要調整正則表達式)
您可以使用正則表達式:
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']
嘗試這個
根據您的輸入!
a = [int(x.split(" ")[0][1:]) for x in s1.split("abc")[1:]]
print(a)
Output
[12, 342, 15]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.