Func
Func

Reputation: 453

Regex to extract numeric string

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.

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.

Upvotes: 3

Views: 990

Answers (5)

Chief
Chief

Reputation: 914

Try using this expression

(\d+\.?\d*|\.\d+)

Upvotes: 0

FailedDev
FailedDev

Reputation: 26940

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

Upvotes: 2

user489998
user489998

Reputation: 4531

Using ^.*[ ;](\d+)[;\n]?$ will capture the numbers you're interested in although you may have to change the \n to \r\n depending on the line endings of your input file.

Upvotes: 1

Aziz Shaikh
Aziz Shaikh

Reputation: 16544

Try this regex:

^(?:[; ]?)(?:.*?)([0-9]+);$

Upvotes: 1

Fischermaen
Fischermaen

Reputation: 12468

The regular expression should be this:

"[; ]{1}[0-9]+($|[^0-9]+)"

Upvotes: 0

Related Questions