Reputation: 86687
I want to check if a string consists of letters and digits only, and allow a -
separator:
^[\w\d-]*$
Valid: TEST-TEST123
Now I want to check that the separator occurs only once at a time. Thus the following examples should be invalid:
Invalid: TEST--TEST
, TEST------TEST
, TEST-TEST--TEST
.
Question: how can I restrict the repeated occurrence of the a character?
Upvotes: 2
Views: 136
Reputation: 626738
You may use
^(?:[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?$
Or, in Java, you may use an alphanumeric \p{Alnum}
character class to denote letters and digits:
^(?:\p{Alnum}+(?:-\p{Alnum}+)*)?$
See the regex demo
Details
^
- start of the string(?:
- start of an optional non-capturing group (it will ensure the pattern matches an empty string, if you do not need it, remove this group!)
\p{Alnum}+
- 1 or more letters or digits(?:-\p{Alnum}+)*
- zero or more repetitions of
-
- a hyphen\p{Alnum}+
- 1 or more letters or digits)?
- end of the optional non-capturing group$
- end of string.In code, you do not need the ^
and $
anchors if you use the pattern in the matches
method since it anchors the match by default:
Boolean valid = s.matches("(?:\\p{Alnum}+(?:-\\p{Alnum}+)*)?");
Upvotes: 3