I need a rather basic Regex.Match syntax - to identify a text line with 2 numbers separated by 2 spaces

Viewed 30

I am a complete rookie at interpreting this syntax... bear with me.

The first number is expected to be after 2 spaces (3rd character), it can be 1 to 5 digits The second number will be just after 2 more spaces (and will be 4 digits or 6 digits only) Currently we use this line, but it is picking up numbers embedded inside of other words.

 Match m = Regex.Match(line, @"\s*\d+\s*(\d{6}|\d{4})"); 
 if (m.Groups.Count > 1)
    ; code to save it as a line element

It needs to capture all of these number sets with the if stastement

1  000233
223  1239
2678  0289
17  002394

And ignore these lines

P_740008_FLT_FG == AFL001
X_234_FLOAT == AFL022

Thanks.

2 Answers

Based off the answer from 'The fourth bird' This was the best solution I ended up, thanks to the clear explanations provided:

       Regex.Match(line, @"^\s*\d+\s+(\d{6}|\d{4})\b");

The key elements I believe were -

  • adding the ^ to signify the 1st # is at the beginning of the line,
  • second was the \b at the end to identify the 2nd # ends at a word boundary.
  • The \s* at the beginning allows 0 or more spaces at the line start, this can happen when it grows to larger 5 digit line numbers, and
  • finally the 2nd \s+ identified at least 1 required space before the next grouped #.

This appears to be working perfectly. Thanks!

The code looks like C#. In that case you can use [0-9] to match a digit from 0-9 as \d matches digits from other languages as well.

Reading the requirements, the pattern would be starting with 2 spaces before and after the 1-5 digits.

To match 1-5 digits, you could use a quantifier for the first part [0-9]{1,5}

Note that \s can also match a newline.

  [0-9]{1,5}  (?:[0-9]{6}|[0-9]{4})\b

To match the examples, you could also start the pattern with a word boundary, and end the pattern with a word boundary as well to prevent partial matches.

\b[0-9]{1,5}  (?:[0-9]{6}|[0-9]{4})\b

.NET regex demo

You can omit the capture group and check for the length. Instead you can use .Success on the Match:

Match m = Regex.Match(line, @"\b[0-9]{1,5}  (?:[0-9]{6}|[0-9]{4})\b");

if (m.Success) {
                
}
Related