簡體   English   中英

以特定格式在字符串中搜索變量 substring

[英]Searching a string for a variable substring in a certain format

想象一下,我正在嘗試查找格式為"XXX"的 substring ,其中 Xs 可以是字符串中的任何 integer 或字符。 我知道在 Python 中,我可以使用string.find("whatever")在字符串中找到一些 substring ,但在這種情況下,我希望找到該格式的任何內容。

例如:

假設我有字符串“你好,我的名字是約翰,我的酒店房間是1.5.3 ,保羅的房間是1.5.4

在這種情況下,我該如何找到“1.5.3”和“1.5.4”?

您想搜索模式而不是已知字符串,您可以將regex與 python re一起使用,這里的方法findall適合

您需要將您的模式傳遞給它,這里\w\.\w\.\w可以, \w代表字母或數字,而\. 對於一個真正的點

import re

value = "Hello, my name is John and my Hotel room is 1.5.3, Paul's room is 1.5.4"
result = re.findall("\w\.\w\.\w", value)
print(result) # ['1.5.3', '1.5.4']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM