简体   繁体   中英

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)—ie not just when surrounded by alphanumerics.

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.

您可以告诉它,三个破折号周围的字符不能是另一个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM