Making a group with spaces between words and decimals

52 Views Asked by At

I'm not new to the concept of regex but the syntax and semantics of everything get confusing for me at times. I have been trying to create a pattern to recognize

Ambient Relative Humidity: 31.59

With the grouping

Ambient Relative Humidity (Group 1)

31.59 (Group 2)

But I also need to be able to match things such as

Operator: Bob

With the grouping

Operator (Group 1)

Bob (Group 2)

Or

Sensor Number: 0001

With the grouping

Sensor Number (Group 1)

0001 (Group 2)

Here is the current pattern I created which works for the examples involving operator and sensor number but does not match with the first example (ambient humidity)

\s*([A-Za-z0-9]*\s*?[A-Za-z0-9]*)\s*:\s*([A-Za-z0-9]*)
3

There are 3 best solutions below

0
On BEST ANSWER

You have to add more space separated key parts to the regex.
Also, you have to add an option for decimal numbers in the value.

Something like this ([A-Za-z0-9]*(?:\s*[A-Za-z0-9]+)*)\s*:\s*((?:\d+(?:\.\d*)?|\.\d+)|[A-Za-z0-9]+)?

https://regex101.com/r/fl0wtb/1

Explained

 (                             # (1 start), Key
      [A-Za-z0-9]* 
      (?: \s* [A-Za-z0-9]+ )*
 )                             # (1 end)
 \s* : \s* 
 (                             # (2 start), Value
      (?:                           # Decimal number
           \d+ 
           (?: \. \d* )?
        |  \. \d+ 
      )
   |                              # or,
      [A-Za-z0-9]+                  # Alpha num's
 )?                            # (2 end)
0
On

I may have posted too soon without thinking, I now have the following expression

\s*([A-Za-z0-9]*\s*[A-Za-z0-9]*\s*[A-Za-z0-9]*)\s*:\s*([A-Za-z0-9.]*)

The only thing is that it includes spaces sometimes that I was trying to avoid but I can just trim those later. Sorry for posting so soon!

0
On
var st = "Ambient Relative Humidity: 31.59 Operator: Bob Sensor Number: 0001";
var li = Regex.Matches(st, @"([\w]+?:)\s+(\d+\.?\d+|\w+)").Cast<Match>().ToList();

    foreach (var t in li)
    {
        Console.WriteLine($"Group 1 {t.Groups[1]}");
        Console.WriteLine($"Group 2 {t.Groups[2]}");
    }

    //Group 1 Humidity:
    //Group 2 31.59
    //Group 1 Operator:
    //Group 2 Bob
    //Group 1 Number:
    //Group 2 0001