2024-04-25 22:24:01 发布
网友
如何从句子中获取数据?在
举个例子 我有这些句子
4 bedroom 2 bath, 1469 sq
然后我在句子中搜索单词'bath',但是从这个句子中我想要得到数字'2',因为它是我的数据。在
我怎么能把那句话中的数字“2”写出来?在
谢谢你
带前瞻断言的正则表达式:
re.search(r"[\d]+(?=\s+bath)", "3 roof 4 bath")
如果你总是有这样的结构:
N word N word, N word
您可以按空格“”拆分并获得2元素。在
您可以使用一个简单的正则表达式来捕获组:
import re s= "3 roof 4 bath" search_word = "bath" res = re.search(r'(\d+)\s*{0}'.format(re.escape(search_word)), s) if res: print(res.group(1))
参见Python demo
详细信息:
(\d+)
[\d,.]+
\d+(?:[,.]\d+)*
\s*
{0}' - a placeholder for the search word whose chars are escaped with
要访问数字,请在match data对象上使用.group(1)。在
.group(1)
带前瞻断言的正则表达式:
如果你总是有这样的结构:
您可以按空格“”拆分并获得2元素。在
^{pr2}$您可以使用一个简单的正则表达式来捕获组:
参见Python demo
详细信息:
(\d+)
-组1:将一个或多个数字捕获到组1中(注意:如果数字可以包含逗号或句点,请使用[\d,.]+
而不是{\d+(?:[,.]\d+)*
)\s*
-0+个空格{0}' - a placeholder for the search word whose chars are escaped with
重新逃逸()`为了匹配,即使其中有特殊的正则表达式字符要访问数字,请在match data对象上使用
.group(1)
。在相关问题 更多 >
编程相关推荐