[英]Replace group for all matches
I only want to replace words in a string, if there is no word character (\\w)
or hyphen before or after the word. 如果在单词之前或之后没有单词字符
(\\w)
或连字符,我只想替换字符串中的单词。
Text: 文本:
#button .button large-button tinybutton size9button #9button button-large buttontiny
Exptected result after replacement: 更换后的预期结果:
#text .text large-button tinybutton size9button #9button button-large buttontiny
Regular Expression: 正则表达式:
(?<![\w-])(button)(?![\w-])
#
). #
之后的按钮)。 What do I need to do to match all occurrences? button
with text
or any other word in Java? text
或其他任何单词替换button
? I have read the topic Can I replace groups in Java regex? 我已阅读主题可以在Java正则表达式中替换组吗? , but I really do not understand how to use the example code for my special case.
,但我真的不明白如何针对我的特殊情况使用示例代码。 Unfortunately I haven't got any code to show.
不幸的是,我没有任何代码可显示。 :/
:/
You can use negative lookbehind and a negative lookahead in replaceAll
method: 您可以在
replaceAll
方法中使用否定的lookbehind和否定的lookahead:
str = str.replaceAll("(?<![\\w-])button(?![\\w-])", "text");
Alternatively you can use lookarounds and word-boundary: 另外,您可以使用环视和单词边界:
str = str.replaceAll("(?<!-)\\bbutton\\b(?!-)", "text");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.