【发布时间】:2021-06-20 14:33:03
【问题描述】:
使用正则表达式我试图只在文本中保留主题标签。我正在尝试匹配其他所有内容并替换为不重要的组。但也许有更聪明的方法。
示例文本:
This is a #text, which is #full of #hashtags.
Well, this is not #easy to
#extract #them.
I think I #start to lose: #hope.
我最好的尝试:([\s\.\,]|^)[^#]\w+([\s\.\,]*?|$)
替换为$2 返回
a #text #full #hashtags #easy
#extract #them. I #start: #hope.
预期结果应该有 4 行,如示例中所示。空间也可以保留。
理想的期望结果:
#text #full #hashtags
#easy
#extract #them
#start #hope
【问题讨论】:
-
没有关于正则表达式引擎和编程语言的确切细节,提供一个简单的答案并不容易。尝试将
(#\w+)|(?:(?!#\w).)+替换为"$1 "(没有")。如果你在 Notepad++ 中工作,它会变得简单得多。 -
使用 PCRE2,您可以使用 conditional replacement。 Boost 也可以这样做,但替换为
(?{1}$1\n:)
标签: regex hashtag regexp-replace