我正在尝试编写一个正则表达式来捕获字符串中的任何测量单位,考虑到该单位可以在数字之前或之后。
我现在想到的是两个正则表达式。
与
匹配的/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
对于显示的示例,请尝试以下正则表达式。
(?:(?:(?:d+)g|(?:gd+))|(?:(?:ls*d+)|(?:d+s*l))|(?:(?:d+,d+s*Kg)|(?:kgs*d+,d+)))
正则表达式的在线演示
解释:为以上内容添加详细说明。
(?: ##Starting 1st capturing group from here.
(?: ##Starting 2nd capturing group from here.
(?:d+)g|(?:gd+) ##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.
(?:ls*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)|(?:kgs*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.
使用不区分大小写的模式,匹配可选的k
和g
或l
,以及替换的|
以另一种方式匹配模式。
可选的点和逗号可以在[.,]?
字符类中,否则.?,?
也可以像.,
一样匹配它们
字边界b
防止单元之后的部分匹配。
d*[.,]?d+s*(?:k?g|l)b|b(?:k?g|l)s*d*[.,]?d+
Regex演示