0

I am having a string like: "abc xyz: ID# 1000123, this is test, test 1, test 1234, "

I need to write a regular expression to extract the ID 1000123.

I have tried some thing like:

Regex betweenOfRegexCompiled = new Regex("ID# (.*), ", RegexOptions.Compiled);

But it gives "1000123, this is test, test 1, test 1234".

So, how to specify the first occurrence of the ", " ?

2
  • 1
    Change "ID# (.*), " to "ID# (.*?), ". Commented May 10, 2013 at 8:35
  • Thanks a lot @ AgentFire Commented May 10, 2013 at 8:38

4 Answers 4

3

Instead of .* use \d+:

"ID# (\d+)"

The .* matches any number of characters. \d+ matches one or more numerals (if you want to exclude non western numerals, use [0-9] instead of \d).

Sign up to request clarification or add additional context in comments.

Comments

3

Here's the (more efficient) non-Regex approach:

string text = "abc xyz: ID# 1000123, this is test, test 1, test 1234, ";
string id = null;
int idIndex = text.IndexOf("ID# ");
if(idIndex != -1)
{
    idIndex += "ID# ".Length;
    int commaIndex = text.IndexOf(',', idIndex);
    if(commaIndex != -1)
        id = text.Substring(idIndex, commaIndex - idIndex);
    else
        id = text.Substring(idIndex);
}

Demo

1 Comment

Nice example usage of Ideone
2

Try this reg, it should take exactly the number

(?<=ID\#\s)\d+(?=\,)

if finds the number after ID# and before ,

Comments

1

Gets the number (i.e. all chars up to, but not including, the first comma) ...

"ID# ([^,]*),"

If you want to make it numbers explicity then...

"ID# ([0-9]*),"

For a non-regex version ...

string text = "abc xyz: ID# 1000123, this is test, test 1, test 1234, ";
string num = text.Split(new Char[] {','})[0].Split(new Char[] {' '})[3];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.