user3132547
user3132547

Reputation: 193

How should I write a regex to match a string with numbers and some specific word?

I have the next regex:

^\s*(\d+(\s*,\s*\d+)*)?\s*$

which matches the next string:

"1, 2, 3"

I need to modify it to match the next string(s) with one specific word(ignore case):

"1, myword, 3"

"myword, 2, 3"

"1, myword, 3, myword"

How can I add additional check group?

Upd: Myword is optional, can repeat several times or be at the beginning of a string.

Upvotes: 1

Views: 57

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627020

You can replace both \d+ with (?:\d+|myword). Have a look at the Alternation with The Vertical Bar or Pipe Symbol:

If you want to search for the literal text cat or dog, separate both options with a vertical bar or pipe symbol: cat|dog. If you want more options, simply expand the list: cat|dog|mouse|fish.

To tell the regex engine we want to only alternate the \d+ digits and myword, we enclose them inside a non-capturing group used only for grouping purposes here.

See

^\s*((?:\d+|myword)(\s*,\s*(?:\d+|myword))*)?\s*$

See the regex demo.

To match MyWoRd case insensitively, use RegexOptions.IgnoreCase flag when compiling the Regex object, or prepend the whole pattern with (?i) inline modifier (i.e. (?i)^\s*((?:\d+|myword)(\s*,\s*(?:\d+|myword))*)?\s*$).

Here is the C# demo:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var inputs = new string[] { "1, 2, 3", "1, myword, 3", "1, MyWord, 3" };
        var pat = @"^\s*((?:\d+|myword)(\s*,\s*(?:\d+|myword))*)?\s*$";
        foreach (var s in inputs)
            Console.WriteLine("{0} matched: {1}", s, Regex.IsMatch(s, pat, RegexOptions.IgnoreCase));
    }

}

Upvotes: 1

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

To start, your original regex can be simplified down to ^\s*(\d+\s*,\s*)*\d+$, which, to deal with your desired extension, can be modified to ^\s*((\d+|myword)\s*,\s*)*\(d+|myword)$.

Upvotes: 1

Related Questions