用正则表达式一次性替换主题标签

Replace hashtags in a single pass with regex

我想用 Java 中的等效标签替换字符串中的所有主题标签。示例:

This is a #foo_bar #document about #nothing_but_tags!

将导致:

This is a foo bar document about nothing but tags!

一次通过正则表达式替换中这可能吗?一个话题标签可能包含很多词。

这里有一个简单的方法:

String str = "#This is a #foo_bar #document about #nothing_but_tags!";
String res = str.replaceAll(" ?#|(?<=#\w{0,100})_", " ").trim();

它会破坏超过 100 个字符的主题标签,如果它恰好是字符串中的第一个东西(因此调用 trim()).

Demo.

100 个字符的限制来自回顾的 {0,100} 部分。这是 Java 正则表达式引擎的局限性:与其他一些正则表达式引擎不同,它要求 look-aneads 和 look-behinds 的长度有一个明确的上限。