co_starr
co_starr

Reputation: 57

Removing words containing expression?

I am looking to remove any words containing "oil". I thought \b grabs any word containing "oil" but seems to only replace the word itself:

String str = "foil boil oil toil hello";
str = str.replaceAll("\\boil\\b", "");

Output:

foil boil toil hello

Desired output:

hello

Upvotes: 1

Views: 1038

Answers (2)

Unihedron
Unihedron

Reputation: 11051

Simply match with prefixing and suffixing [a-z]*!

Match (and replace):

/ ?[a-z]*oil[a-z]* ?/

View an online regex demo.

Upvotes: 3

hwnd
hwnd

Reputation: 70732

A word boundary asserts that on one side there is a word character, and on the other side there is not.

You can use the following regex:

String s = "foil boil oil toil hello";
s = s.replaceAll("\\w*oil\\w*", "").trim();
System.out.println(s); //=> "hello"

Or if you want to be strict on just matching letters.

String s = "foil boil oil toil hello";
s = s.replaceAll("(?i)[a-z]*oil[a-z]*", "").trim();
System.out.println(s); //=> "hello"

Upvotes: 2

Related Questions