REGEX Matching string nonconsecutively

Viewed 59

I'm trying to understand how to match a specific string that's held within an array (This string will always be 3 characters long, ex: 123, 568, 458 etc) and I would match that string to a longer string of characters that could be in any order (9841273 for example). Is it possible to check that at least 2 of the 3 characters in the string match (in this example) strMoves? Please see my code below for clarification.

    private readonly string[] strSolutions = new string[8] { "123", "159", "147", "258", "357", "369", "456", "789" };
    Private Static string strMoves = "1823742"

    foreach (string strResult in strSolutions)
       {
            Regex rgxMain = new Regex("[" + strMoves + "]{2}");
            if (rgxMain.IsMatch(strResult))
            {
                MessageBox.Show(strResult);
            }
        }

The portion where I have designated "{2}" in Regex is where I expected the result to check for at least 2 matching characters, but my logic is definitely flawed. It will return true IF the two characters are in consecutive order as compared to the string in strResult. If it's not in the correct order it will return false. I'm going to continue to research on this but if anyone has ideas on where to look in Microsoft's documentation, that would be greatly appreciated!

Correct order where it would return true: "144257" when matched to "123" incorrect order: "35718" when matched to "123" The 3 is before the 1, so it won't match.

1 Answers

You can use the following solution if you need to find at least two different not necessarily consecutive chars from a specified set in a longer string:

new Regex($@"([{strMoves}]).*(?!\1)[{strMoves}]", RegexOptions.Singleline)

It will look like

([1823742]).*(?!\1)[1823742]

See the regex demo.

Pattern details:

  • ([1823742]) - Capturing group 1: one of the chars in the character class
  • .* - any zero or more chars as many as possible (due to RegexOptions.Singleline, . matches any char including newline chars)
  • (?!\1) - a negative lookahead that fails the match if the next char is a starting point of the value stored in the Group 1 memory buffer (since it is a single char here, the next char should not equal the text in Group 1, one of the specified digits)
  • [1823742] - one of the chars in the character class.
Related