简体   繁体   中英

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. 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

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

This only gives me result if the input has int like 12m not 12.m or 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:
    • \\d*\\.?\\d+ - 0+ digits, an optional . , 1+ digits
    • | - or
    • \\d+\\.?\\d* - 1+ digits, an optional . , 0+ digits
  • ) - end of Capturing group 1
  • \\s* - 0+ whitespaces
  • ([az]+) - Capturing group 2: one or more lowercase letters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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