Rejecting certain regex patterns
I am new to regex and am trying to match a string that
- may be long
- may be alphanumeric and may also contain
$
,-
or/
- cannot contain more than two of these non-alphanumeric characters in a string or end with
/
or-
.
For example, Hello/World
is valid, Hello//World
is invalid.
I've tried a couple of different possibilities, with this one getting closer to working as I expect:
^--|-/|/-|\s\s|$$|$-|-$|$/|/$|//|([a-zA-Z0-9 -$/])*(?<![/-])$
This seems to be sufficient for every scenario, except when the two forward slashes are together. Do I need to escape the leading slashes, or is it because my matching expression is too large and swallowing bad lines? I've tried different expressions with negative look and feel, but they all run into problems, especially with false negatives.
Greetings,
Jeff
+3
source to share
2 answers
Here's the regex you're looking for:
^(?![^/$-]*[/$-]{2})[\w/$-]+(?<![/-])$
Regex Demo and IDEONE Java Demo
String str1 = "Hello/World";
String str2 = "Hello//World";
String ptrn = "^(?![^/$-]*[/$-]{2})[\\w/$-]+(?<![/-])$";
System.out.println(str1.matches(ptrn)); // => true
System.out.println(str2.matches(ptrn)); // => false
Explanation:
-
^
- beginning of line (optional inmatches()
) -
(?![^/$-]*[/$-]{2})
- Lookahead ensuring that the string contains at most 1 non-alphanumeric character -
[\w/$-]+
- the class of the base character corresponding to the alphanumeric characters and/
,$
or-
-
(?<![/-])
- Make sure the string does not end with prohibited non-alphanumeric characters. -
$
- End of line (optional inmatches()
)
+1
source to share