2

I only want to replace words in a string, if there is no word character (\w) or hyphen before or after the word.

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?

I have read the topic Can I replace groups in Java regex?, 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. :/

Community
  • 1
  • 1
Max Peterson
  • 129
  • 1
  • 1
  • 4

1 Answers1

0

You can use negative lookbehind and a negative lookahead in replaceAll method:

str = str.replaceAll("(?<![\\w-])button(?![\\w-])", "text");

Alternatively you can use lookarounds and word-boundary:

str = str.replaceAll("(?<!-)\\bbutton\\b(?!-)", "text");

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643