2

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?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
E.Simchuk
  • 77
  • 4

3 Answers3

1
[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\.

See it in action

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
1

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 dot

See demo at Regexplanet (click Java)

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46
1

This works for your test cases:

[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.

See live demo.

Bohemian
  • 412,405
  • 93
  • 575
  • 722