C# Regex Match text until specific character

2.6k Views Asked by At

I'm trying to get a regex to validate/extract from a string all the characters until the first dollar. If the string doesn't have any dollar,it should match the whole string but it doesn't work.

What i tested is:

System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match("12345678$1", "/[^\$]*/");

What i expect is to get in match.value => 12345678 If the string passed is for example 123456781 it should return everything.

What is wrong?

Thanks Best regards.

5

There are 5 best solutions below

0
On

From what I am getting, the expression you are using will match any string which is made up from 0 or more instances of any non $ character.

You could try something like below:

        string sample = "1234578";
        Regex regex = new Regex("(.+?)(\\$|$)");
        if (regex.IsMatch(sample))
        {
            Match match = regex.Match(sample);
            Console.WriteLine(match.Groups[1]);
        }

Which matches and extracts any numbers up to $ (denoted as \\$) or else, the end of the string (denoted by $), which ever comes first.

1
On
System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match("12345678$1", "(.+)\\$");

And your result will be in match.Groups[1]

2
On

You forget to escape your \:

Match match = Regex.Match("12345678$1", "[^\\$]*");
Console.WriteLine(match.Value);
match = Regex.Match("123456781", "[^\\$]*");
Console.WriteLine(match.Value);

Outputs:

12345678
123456781

As pointed out by dolgsthrasir you don't need to escape $ in your regexp so "[^$]*" is fine.

1
On

Try with this

System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match("12345678$1", "([^\\$]+)");

extracted string should be group 1.

0
On

You don't need regex, you can just use IndexOf and SubString

var str = "12345678$1";
int index = str.IndexOf("$");
if(index < 0)
    return str;
else
    return str.Substring(0, index);

Example