Reputation: 3526
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:
sss
sdfsgdf
4534534
dfs34543
sdafds+3232+sfdsafd
qwe+sdf
234+567
cvb+243
a
aa
a+
aa+
+aa
+a
a+a
aa+aa
aaa+a
Upvotes: 3
Views: 916
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 inputEdit: 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,})*$
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,})*$
Upvotes: 4
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 stringUpvotes: 2