why is this regex not working?

shahar 1 Reputation point
2021-08-24T14:23:23.917+00:00

I have this regex [\\p{L}]+([\\p{L}]|[\\d])+([ ]?[\\p{L}]+([\\p{L}]|[\\d])+)? the idea is to recognize at least 2 words with a space between them that each of the words has at least 2 letters.

for some reason it recognize "aa"

any idea what am I doing wrong?

Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-08-24T14:33:02.31+00:00

    Try removing both of '?'.


  2. Jack J Jun 25,296 Reputation points
    2021-08-25T07:05:53.193+00:00

    @shahar , you could try the regex string "^([a-zA-Z]{2,}[\\s[a-zA-Z]]*)+$" to validate a string at least contains two words and every word at least contains two character.

    Based on my test, you can refer to the following code to validate the string.

    Code:

      var regex = "^([a-zA-Z]{2,}[\\s[a-zA-Z]]*)+$";  
                string[] arr = { "aa", "a goog boy", "an email", "the test email" };  
                foreach (var item in arr)  
                {  
                    Match ma= Regex.Match(item, regex, RegexOptions.IgnoreCase);  
                    Console.WriteLine(item +" ***** "+ma.Success);  
                }  
    

    Note: {2,} shows that a word must at least two characters. [\\s[a-zA-Z]] indicates that one or more spaces followed by letters.
    Result:

    126274-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.