Hitesh Kansagara
Hitesh Kansagara

Reputation: 3526

Regular Expression that matches when any string has minimum three characters, and + signs are surrounded by minimum three characters

I wanted to create regex expression that only matches when any string has three or more character and if any + sign in the string then after and before + sign it must be minimum three characters required,

I have created one regex it fulfills me all requirement except one that before first + sign must be minimum three characters but it matches with less character

this is my current regex: (\+[a-z0-9]{3}|[a-z0-9]{0,3})$

ab+abx this string should not match but it matched in my regex

Example:

Valid Strings:

sss
sdfsgdf
4534534
dfs34543
sdafds+3232+sfdsafd
qwe+sdf
234+567
cvb+243

Invalid Strings:

a
aa
a+
aa+
+aa
+a
a+a
aa+aa
aaa+a

Upvotes: 3

Views: 916

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex,

^[^+\n]{3,}(?:\+[^+\n]{3,})*$

Explanation:

  • ^ - Start of string
  • [^+\n]{3,} - This ensures it matches any characters except + and newline, \n you can actually remove if the input you're trying to match doesn't contain any newlines and {3,} allows it to match at least three and more characters

  • (?:\+[^+\n]{3,})* - This part further allows matching of a + character then further separated by at least three or more characters and whole of it zero or more times to keep appearance of + character optional

  • $ - End of input

Demo

Edit: Updating solution where a space does not participate in counting the number of characters in either side of + where minimum number of character required were three

You can use this regex to ignore counting spaces within the text,

^(?:[^+\n ] *){3,}(?:\+ *(?:[^+\n ] *){3,})*$

Demo

Also, in case you're dealing with only alphanumeric text, you can use this simpler and easier to maintain regex,

^(?:[a-z0-9] *){3,}(?:\+ *(?:[a-z0-9] *){3,})*$

Demo

Upvotes: 4

The fourth bird
The fourth bird

Reputation: 163362

You could repeat 0+ times matching 3 or more times what is listed in the character class [a-z0-9] preceded by a plus sign:

^[a-z0-9]{3,}(?:\+[a-z0-9]{3,})*$

That will match:

  • ^ Start of string
  • [a-z0-9]{3,} Match 3+ times what is listed in the character class
  • (?: Non capturing group
    • \+[a-z0-9]{3,} Match + sign followed by matching 3+ times what is listed in the character class
  • )* Close group and repeat 0+ times
  • $ End of string

Upvotes: 2

Related Questions