简体   繁体   English

使用正则表达式提取字符串后跟带有空格的数字

[英]Extract strings followed by number with space using regex

I have the follwing string我有以下字符串

[1] weight | width | depth | 5.0 kg | 6.0 mm^3 | 10.12 cm^2

From that I need to extract the unit strings only从中我只需要提取单位字符串

unit=kg
unit=mm^3
unit=cm^2

I tried the below regex我尝试了下面的正则表达式

(?<unit>[^ -+0-9\\.\|\[\}\]]+)

But it is also giving the weight,width,depth values too.但它也给出了重量、宽度、深度值。 Also tried也试过

(?<unit>[\D][^|]+)

but not worked.但没有奏效。 I think I need to extract the strings which are followed by number and space我想我需要提取后面跟着数字和空格的字符串

Can you help me on this你能帮我解决这个问题吗

You could use a character class to list the allowed characters:您可以使用字符类列出允许的字符:

\b[0-9]+(?:\.[0-9]+)?[^\S\r\n]+(?<unit>[a-z^0-9]+)\b

Regex demo正则表达式演示

Or more specific:或更具体:

\b[0-9]+(?:\.[0-9]+)?[^\S\r\n]+(?<unit>kg|[mc]m)\b

See another regex demo查看另一个正则表达式演示

If there should be either a pipe or the end of the string:如果应该有管道或字符串的末端:

\b[0-9]+(?:\.[0-9]+)?[^\S\r\n]+(?<unit>[^0-9\s]\S*)(?:[^\S\r\n]+\||$)

Regex demo正则表达式演示

I have used below regex, and it is matching only unit string.我在下面使用了正则表达式,它只匹配单位字符串。

 \b[a-z]{2}(?:[\^]\d+)?(?!\S)\b

Demo link : https://regex101.com/r/AjONqR/1演示链接: https ://regex101.com/r/AjONqR/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM