ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

Java regex to match an exact number of dashes

In my Markdown-like text, I want to replace exactly three dashes (---) with an emdash entity, but I don't want to replace four dashes.

How can I write this as a regex?

I tried this:

String input = "--- This---example----and--another.---";
String expected = "— This—example----and--another.—";
assertEquals(expected, input.replaceAll("-{3}", "—"));

But it gives me:

— This—example—-and--another.—

Instead of what I want:

— This—example----and--another.—

I want it to work when three dashes appear at the start or end of a line or with any surrounding characters (other than dashes)—i.e. not just when surrounded by alphanumerics.

Upvotes: 2

Views: 214

Answers (2)

Stik
Stik

Reputation: 607

You can tell it that the character around the 3 dashes mustn't be another one:

replaceAll("[^-]-{3}[^-]", ...)

Upvotes: -1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627264

Use lookarounds to make sure only 3 dashes are matched:

input.replaceAll("(?<!-)-{3}(?!-)", "&#8212;")

See the regex demo

The (?<!-) negative lookbehind will fail the match once a - is before the 3 dashes, and (?!-) negative lookahead will fail the match if there is a - after 3 dashes.

Upvotes: 6

Related Questions