Reputation: 87
I have a wrong regex
([A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]*\.)
I need to accept strings like:
a-b.
ab.
a.
But i am not needing in this string - a-.
What should I change?
Upvotes: 2
Views: 1859
Reputation: 425043
This works for your test cases:
[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.
See live demo.
Upvotes: 1
Reputation: 18490
You can try like this by using an optional group.
"(?i)[A-Z0-9](?:-?[A-Z0-9]+)*\\."
(?i)
flag for caseless matching.[A-Z0-9]
one alphanumeric character(?:-?[A-Z0-9]+)*
any amount of (?:
an optional hyphen followed by one or more alnum )
\.
literal dotSee demo at Regexplanet (click Java)
Upvotes: 1
Reputation: 36100
[A-Za-z0-9]+\.|[A-Za-z0-9]+-?[A-Za-z0-9]\.
The idea is:
-?
- optional dash\.
- escaped dot, to match literal dot|
- alternation (one or the other)x+
- one or more repetitions, equivalent to xx*
If you don't mind matching underscores too, you can use the word character set:
\w+\.|\w+-?\w\.
Upvotes: 1