Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract numeric string

Tags:

c#

.net

regex

Hi I don't feel very well with regular expressions. What I would like to achieve is to extract a numeric substring (only 0-9 digits) from the input string.

  • The numeric string that is searched should be preceded only by a semicolon (;), space ( ) or should be placed exactly at the begining of the input (not line).
  • The numeric string that is searched should be followed only by a semicolon (;), the end of line or the end of the input string.

Exemplary input:

;x; ;SrvId=3993;ad257c823; 435223;

Output:

435223

I tried: [ \A|;|[ ]]\d*[\r|;|\Z] but it did not worked, it did not even compiled.

like image 608
Func Avatar asked Jun 15 '26 01:06

Func


1 Answers

Try this one:

string resultString = null;
try {
    resultString = Regex.Match(subjectString, @"(?<=\A|\s+|;)(\d+)(?=$|;|\Z)").Groups[1].Value;
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

Break down :

(?<=\A|\s+|;)

Posiive lookbehind : start of input or at least one whitespace character or a semicolon.

(\d+) at least one digit

(?=$|;|\Z)

Positive lookahead either end of line, or semicolon or and of input.

Input : ;x; ;SrvId=3993;ad257c823; 435223;

Output of group 1 : 435223

like image 70
FailedDev Avatar answered Jun 16 '26 15:06

FailedDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!