Regex match pattern plus rest of the string until next dot, comma or space

Viewed 372

Let's say I have a string WORK-232-3213-2323. Known possible case scenarios:

WORK-232-3213-2323, some text
WORK-232-3213-2323. some text
WORK-232-3213-2323.xlsx
WORK-232-3213-2323 some text
WORK-232-3213-2323/some text

Format WORK-232-3213-2323-some text may also occur, but there is no need to handle this case

My current regex is able to catch needed strings with WORK-232-3213-2323 pattern, but as an output I get -232-3213-2323. How to make it so that it would catch WORK- in string plus rest of the text until next whitespace, dot, slash or comma?

Current regex: WORK-(.*?)[\s]

C#:

Regex pattern = new Regex("WORK-(.*?)[\s]");
string result = pattern.Match(myString).Groups[1].Value
2 Answers

You might use a match without using a capture group and use a negated character class excluding a comma, dot or whitspace char.

\bWORK-[^.,\s]+
  • \bWORK- Match WORK preceded by a word boundary to prevent a partial match
  • [^.,\s]+ Negated character class to match 1+ times any char except . , or a whitspace char

Regex demo

string[] strings = { 
    "WORK-232-3213-2323, some text",
    "WORK-232-3213-2323. some text",
    "WORK-232-3213-2323.xlsx",
    "WORK-232-3213-2323 some text",
    "WORK-232-3213-2323/some text"
    };
string pattern = @"\bWORK-[^.,\s]+";
foreach (String s in strings) {
    Console.WriteLine(Regex.Match(s, pattern).Value);
}

Output

WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323/some

If you don't want to match the last line, you could use the capture group and match a . , or whitespace char after it

\b(WORK-[^.,\s\/]+)[.,\s]

Regex demo

For example using the same example strings:

string pattern = @"\b(WORK-[^.,\s\/]+)[.,\s]";
foreach (String s in strings) {
    Console.WriteLine(Regex.Match(s, pattern).Groups[1].Value);
}

Output

WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323

Looks to me you can use the following pattern to handle all your cases, also the one that may occur:

\bWORK(?:-[0-9]+)+

See an online demo

I'm no hero in c# so I used some code I could find to test this:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var s = @"WORK-232-3213-2323, some text";
        var pattern = @"\bWORK(?:-[0-9]+)+";
        
        Regex r = new Regex(pattern);       
        
        Match m = r.Match(s);
        if (m.Success) 
        {
            Console.WriteLine(m.Value);
        }
    }
}

Alternatively you can use \bWORK(?:-\d+)+ and use Regex r = new Regex(pattern, RegexOptions.ECMAScript); with the ECMAScript option set.

Related