Python regex,用于检索多个值,其中包含不同的给定单词



需要从文本中检索尺寸,可以通过两种方式指定:

  • "…10.5英寸x 5英尺x 2英寸…">
  • "…10英寸x 5英寸…">
  • "…10英寸x 5英寸…">
  • "…10 x 5英寸…">

可以有两个或三个维度,每个维度可以有自己的测量类型,也可以没有。

我正在努力添加可选维度类型的列表,并在正则表达式中搜索第三个可选值:

dimensions = re.findall(r'(d+.?d*)s*inches?feet?s*xs*(d+.?d*)s*inches?feet?s*x?s*(d+.?d*)?s*inches?feet?',string)

您所拥有的是inches?feet?,它表示"匹配0到1 '英寸'和0到1 '英尺'"。这意味着它可以匹配"5 inchesfeet"之类的内容。

你已经很接近了。您错过的关键思想是,|可用于指定匹配的备选方案:(?:inches|feet)?。他们被放在一个非捕获组,以澄清只有"脚";应该是替代方案的一部分,而不是之后的一切。最后的?使整个组可选。

要使整个第三维可选,可以将其模式放在非捕获组中,然后可以使用?:

将该组设置为可选。
(?:xs*(d+.?d*)?s*(?:inches|feet)?)?

最终的正则表达式是

(d+.?d*)s*(?:inches|feet)?s*xs*(d+.?d*)s*(?:inches|feet)?s*(?:xs*(d+.?d*)?s*(?:inches|feet)?)?

这是一个正在工作的re.findall方法:

inp = """... 10 inches x 5 feet x 2 inches ...
... 10 inches x 5 inches ..."
... 10 inches x 5 inches ..."
... 10 x 5 inches ..."""
dims = re.findall(r'd+(?:.d+)?(?: (?!xb)w+)?(?: x d+(?:.d+)?(?: (?!xb)w+)?)*', inp)
print(dims)

这个打印:

['10 inches x 5 feet x 2 inches',
'10 inches x 5 inches',
'10 inches x 5 inches',
'10 x 5 inches']

下面是对使用的regex模式的解释:

d+(?:.d+)?           match a number
(?:
[ ]                 followed by space
(?!xb)             NOT followed by 'x'
w+                 but is followed by any other dimension
)?                      optional
(?:
[ ]                 space
x                   'x'
[ ]                 space
d+(?:.d+)?       another number
(?: (?!xb)w+)?    zero or more other numbers/dimensions
)*                      optional

最新更新