E.Simchuk
E.Simchuk

Reputation: 87

How get the priority in regex?

I have a wrong regex

([A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]*\.)

I need to accept strings like:

But i am not needing in this string - a-.

What should I change?

Upvotes: 2

Views: 1859

Answers (3)

Bohemian
Bohemian

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

bobble bubble
bobble bubble

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 dot

See demo at Regexplanet (click Java)

Upvotes: 1

ndnenkov
ndnenkov

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

See it in action

Upvotes: 1

Related Questions