简体   繁体   English

如何使用正则表达式从C#中的字符串中提取数字(整数或双精度)和文本

[英]How to extract a number (integer or double) and text from a string in C# with regular expression

I am trying to build a small unit conversion in C# and I am countering a problem. 我正在尝试在C#中建立一个小的单位转换,并且我正在解决一个问题。 I looked in to a few examples on the internet but I failed to apply 我查看了互联网上的一些示例,但未能申请

Example text input:
12m 
12 m
12.4m
.5m
12.m

I would like to string num and string unit 我想string numstring unit

new Regex(@"([\d.])([a-zA-Z- -/]+)");

This only gives me result if the input has int like 12m not 12.m or 12.4m... 仅当输入具有12m而不是12.m12.4m... int这才给我结果12.4m...

I could work around to include . 我可以解决这个问题. in the input text but now the input has to have . 在输入文本中,但现在输入必须具有. , also happens with the decimal part. ,也发生在小数部分。

new Regex(@"([\d.][.][\d.])([a-zA-Z- -/]+)");

Although I could do multiple possible cases to handle different input formats, the code looks bad. 尽管我可以做多种可能的情况来处理不同的输入格式,但是代码看起来很糟糕。 Any help is appreciated. 任何帮助表示赞赏。

You may use 您可以使用

(\d*\.?\d+|\d+\.?\d*)\s*([a-z]+)

See the regex demo 正则表达式演示

Details 细节

  • ( - start of the Capturing group 1: ( -捕获组1的开始:
    • \\d*\\.?\\d+ - 0+ digits, an optional . \\d*\\.?\\d+ -0 \\d*\\.?\\d+位数字,可选. , 1+ digits ,1个以上的数字
    • | - or - 要么
    • \\d+\\.?\\d* - 1+ digits, an optional . \\d+\\.?\\d* -1+位数字,可选. , 0+ digits ,0位数以上
  • ) - end of Capturing group 1 ) -捕获组1的结尾
  • \\s* - 0+ whitespaces \\s* -0+空格
  • ([az]+) - Capturing group 2: one or more lowercase letters. ([az]+) -捕获组2:一个或多个小写字母。

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

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