Detecting a numeric string that does not have '$' at the beginning of a numeric string in a read string after denying a regular expression

Asked 2 years ago, Updated 2 years ago, 57 views

.NET 4.5
input="abc123def $456ghi" (Note string and numeric string are both random)
I want to find a string of digits that does not have $ at the beginning (I want to find 123 only)
pattern="(?\<!\$)\d+"
If you do it in , it will be "123", "56".

Please tell me who knows the solution.
Also, I would appreciate it if you could reply that it is impossible to use regular expressions alone.

.net regular-expression

2022-09-29 22:22

2 Answers

In the questionnaire, "Negative Post-Reading" was answered by pgrho and unarist, but please explain it separately.
Taking advantage of the regular expression in the .NET Framework being the same traditional NFA engine as Perl, Python, Emacs, Tcl, JavaScript, etc.

var input="abc123def $456ghi";
var pattern=@"\$\d*|(\d+)";
foreach(Match min Regex.Matches(input, pattern)){
    if(m.Groups[1].Success)
        Console.WriteLine(m.Groups[1].Value);
}

You can obtain "123" in .
\$\d* takes in '$' and subsequent numbers because it is captured as long as it matches with a traditional NFA engine.The undesirable "$456" matches here and does not flow next.If not, it matches (\d+), so capture it as a group.
However, even if it matches in the first half, it is m.Success, so narrow it down to m.Groups[1].Success.

If you understand the characteristics of the regular expression engine itself, it is useful beyond the .NET Framework.For example, in the case of JavaScript, there is no post-reading, but I can express the pattern I mentioned.

Also on pgrho and unarist's approach using "Negative Post-Reading".

var pattern=@"\d+(?<!\$\d+);

But I can do it.This is a numerical value, which matches both "123" and "456".Then exclude "$456" where '$' precedes ', and only "123" matches.
I think this pattern makes the contents of regular expressions easy for people to read.(Performance should also be good, since you don't have to check the reading after negating one character at a time.)


2022-09-29 22:22

var pattern=@"(?<=[^$\d])\d+";

As shown in , you should look for $ or non-numeric characters.However, this does not include the first digit of the string, so

var pattern=@"(^|(?<=[^$\d]))\d+";

and ^ must also be added.


2022-09-29 22:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.