1

basically in need that a whole string is a match if it has the following pattern:

DIGITS SPACE WORDS(min. 1 to a max of 3.) SPACE

So the following string will be a match:

30 boxes 30 boxes 30 boxes boxes boxes 

But the following won't match:

30 boxes 30 boxes boxes boxes boxes 30 boxes 

NOTE: the last character in a row is a space

I have the following regex up until now:

(\d+)(\s)(([a-zA-Z]+)(\s)){1,3}
4
  • By "strings" do you mean "letters" or "words" or something else? Also, I can't understand why the first example matches and the seconds one does not. Please clarify your question. Commented Dec 30, 2018 at 21:30
  • The 1st one is satisfied because between each pair of integers there are a max. of 3 words i.e. boxes is written 3 times. In the 2nd instance, there is boxes written 4 times which should be incorrect as stated by the regex statement {1,3} Commented Dec 30, 2018 at 22:01
  • Try ^(?:\d+(?:\s+[a-zA-Z]+){1,3}\s*)+$, see demo Commented Dec 31, 2018 at 1:00
  • @wiktor feel free to post your comment as an answer Commented Dec 31, 2018 at 16:11

2 Answers 2

1

I suggest using

^(?:\d+(?:\s+[a-zA-Z]+){1,3}\s*)+$

See the regex demo

It matches

  • ^ - start of string
  • (?:\d+(?:\s+[a-zA-Z]+){1,3}\s*)+ - one or more occurrences of
    • \d+ - 1 or more digits
    • (?:\s+[a-zA-Z]+){1,3} - one, two or three occurrences of
      • \s+ - 1+ whitespaces
      • [a-zA-Z]+ - 1+ ASCII letters
  • \s* - 0+ whitespaces
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

2 Comments

Your pattern doesn't work for "30 boxes 30 boxes boxes boxes boxes 30 boxes " case.
@JohnyL It should fail, so it works. boxes boxes boxes boxes contains 4 words and the requirement is min. 1 to a max of 3..
1
var s = "30 boxes 30 boxes boxes boxes boxes 30 boxes ";
var pattern = @"(?i)^(\d+(\s+[a-z]+\s*)+){1,3}$";
WriteLine($"Is match: {Regex.IsMatch(s, pattern)}"); // => Is match: true

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.