[英]Searching a string for a variable substring in a certain format
Imagine I'm trying to find a substring formatted as "XXX" , in which the Xs can be any integer or character, in a string.想象一下,我正在尝试查找格式为"XXX"的 substring ,其中 Xs 可以是字符串中的任何 integer 或字符。 I know that in Python I can use
string.find("whatever")
to find some substring within a string, but in this case, I'm looking to find anything that is in that format.我知道在 Python 中,我可以使用
string.find("whatever")
在字符串中找到一些 substring ,但在这种情况下,我希望找到该格式的任何内容。
For example:例如:
Say I have the string "Hello, my name is John and my Hotel room is 1.5.3 , Paul's room is 1.5.4 "假设我有字符串“你好,我的名字是约翰,我的酒店房间是1.5.3 ,保罗的房间是1.5.4 ”
How do I go about finding "1.5.3" and "1.5.4" in this case?在这种情况下,我该如何找到“1.5.3”和“1.5.4”?
You want to search for a pattern and not a known string, you may use regex
with python package re
and here method findall
would fit您想搜索模式而不是已知字符串,您可以将
regex
与 python re
一起使用,这里的方法findall
适合
You need to pass it your pattern, here \w\.\w\.\w
would be ok, \w
is for a letter or digit, and \.
您需要将您的模式传递给它,这里
\w\.\w\.\w
可以, \w
代表字母或数字,而\.
for a real point对于一个真正的点
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.