简体   繁体   English

替换所有比赛的组

[英]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-])
  1. The regular expression currently only matches the first occurrence (button after # ). 正则表达式当前仅匹配第一个匹配项( #之后的按钮)。 What do I need to do to match all occurrences? 我该怎么做才能匹配所有事件?
  2. How can I replace button with text or any other word in Java? 如何用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");

RegEx Demo 正则演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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