Home > Enterprise >  Match numbers that not in context of Value(x)
Match numbers that not in context of Value(x)

Time:10-01

I am trying to match the numbers that are not in the context of Value(X) and discard rest of text.

Example text:

 lorem ipsum Value (3) dfasdf 654345435ds sdfsdf asdf
asd
F
asdf
sad Value (2)

Example Regex:

 Value\((\d)\)

I need to match just the numbers not in context of Value(x) and discard rest of text:

enter image description here

Thanks for help.

CodePudding user response:

You are looking for:

(?<!Value *\()\d )

Note that I am assuming that every Value( has a closing bracket.

Explanation:

  • (?<!Value *\() asserts that what follows it is not preceded by "Value(", Value (, Value ( and so on.
  • \d matches a digit between one and infinite times

CodePudding user response:

Something like this ought to do you:

private static readonly Regex rx = new Regex(@"
  (?<!          # A zero-width negative look-behind assertion, consisting of:
    \w          #   - a word boundary, followed by
    Value       #   - the literal 'Value', followed by
    \s*         #   - zero or more whitespace characters, followed by
    [(]         #   - a left parenthesis '(', followed by
    \s*         #   - zero or more whitespace characters,
  )             # The whole of which is followed by
  (             # A number, consisting of
    -?          #   - an optional minus sign, followed by
    \d          #   - 1 or more decimal digits,
    )           # The whole of which is followed by
  (?!           # A zero-width negative look-ahead assertion, consisting of
    \s*         #   - zero or more whitespace characters, followed by
    [)]         #   - a single right parenthesis ')'
  )             #
",
    rxOpts
  );

private const RegexOptions rxOpts = RegexOptions.IgnoreCase
                                  | RegexOptions.ExplicitCapture
                                  | RegexOptions.IgnorePatternWhitespace
                                  ;

Then . . .

foreach ( Match m in rx.Matches( someText ) )
{
  string nbr = m.Value;
  Console.WriteLine("Found '{0}', nbr);
}

CodePudding user response:

The .NET regex engine supports a quantifier in the lookbehind assertion.

What you might do is assert that from the current position, the is not Value( to the left that has 1 digits and ) to the right. If that is the case, match 1 or more digits.

The pattern matches:

(?<!\bValue[\p{Zs}\t]*\((?=[0-9] \)))[0-9] 
  • (?<! Positive lookbehind, assert what is to the left is
    • \bValue Match Value preceded by a word boundary to prevent a partial match
    • [\p{Zs}\t]*\( Match optional horizontal spaces followed by (
    • (?=[0-9] \)) Positive lookahead, assert 1 digits followed by ) to the right
  • ) Close lookbehind
  • [0-9] Match 1 digits 0-9

enter image description here

  • Related