正则表达式:匹配数值两侧的计量单位 (200 g/g 200)。

3

我正在尝试编写一个正则表达式,以捕获字符串中的任何计量单位,考虑到单位可能在数字之前或之后。

目前我想到的有两个正则表达式。

/\d*\.?,?\d+\s?(kg|g|l)/gi 用于匹配

ABC 200g
EFG 5,4 Kg
HIL 2x20l

( kg | g | l )\s? \d+ ,?\.? d* 匹配以下内容:

ABC g200
EFG kg 5,4
HIL l 20x2

怎样将两个正则表达式结合起来以匹配两种情况:

ABC g200
EFG 5,4 Kg
2个回答

3

请使用您展示的样例,尝试以下正则表达式。

(?:(?:(?:\d+)g|(?:g\d+))|(?:(?:l\s*\d+)|(?:\d+\s*l))|(?:(?:\d+,\d+\s*Kg)|(?:kg\s*\d+,\d+)))

上面正则表达式的在线演示

说明:为上述内容添加详细说明。

(?:                                     ##Starting 1st capturing group from here.
  (?:                                   ##Starting 2nd capturing group from here.
     (?:\d+)g|(?:g\d+)                  ##Matching either digits followed by g OR g followed by digits(both conditions in non-capturing groups here).
  )                                     ##Closing 2nd capturing group here.
  |                                     ##Putting OR condition here.
  (?:                                   ##Starting 3rd capturing group here.
     (?:l\s*\d+)|(?:\d+\s*l)            ##Matching eiter l followed by 0 or more spaces followed by digits OR digits followed by 0 or more spaces followed by l.
  )                                     ##Closing 3rd capturing group here.
  |                                     ##Putting OR condition here.
  (?:                                   ##Starting 4th capturing group here.
     (?:\d+,\d+\s*Kg)|(?:kg\s*\d+,\d+)  ##Checking either digits followed by comma digits spaces Kg OR kg spaces digits comma digits here.
  )                                     ##Closing 4th capturing group here.
)                                       ##Closing 1st capturing group here.

2
使用不区分大小写的模式,匹配可选的 kgl 并使用交替项 | 以相反的方式匹配该模式。
可选的点号和逗号可以在字符类 [.,]? 中,或者使用 .?,? 来同时匹配 .,
词边界 \b 可以防止在单位之后出现部分匹配。
\d*[.,]?\d+\s*(?:k?g|l)\b|\b(?:k?g|l)\s*\d*[.,]?\d+

Regex demo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接