Ziemniak.TV
Ziemniak.TV

Reputation: 3

Java regex - delete phrase from string if its not beginning of word

Example

"I'am peter and i'm apetering or fadapetering"

Phrase: pet

Result:

I'am peter and i'm aering or fadaering"

I need to delete phrase for example "pet" if it's not beginning of word!

While using normal regex i'm having trouble 'cause i'm deleting beginning of word too:

outs = textOuts.replaceAll("\\w+" + givePhrase, "");

Every is on Strings.

Upvotes: 0

Views: 67

Answers (3)

Bohemian
Bohemian

Reputation: 425268

You don't even need a look behind:

outs = textOuts.replaceAll("\\B" + givePhrase, "");

The regex expression \B means "not a word boundary" (the opposite of \b "word boundary").

Upvotes: 1

Mena
Mena

Reputation: 48434

Use a positive lookbehind for this.

String input = "I'am peter and i'm apetering or fadapetering";
System.out.println(
    input
    .replaceAll("(?<=\\w)pet", "")
);

Output

I'am peter and i'm aering or fadaering

Note

See API on Special constructs (named-capturing and non-capturing).

Upvotes: 0

vks
vks

Reputation: 67988

(?<!\\s|^)pet

Try this.See demo.Replace by empty string.

http://regex101.com/r/gJ4uX1/1

Upvotes: 0

Related Questions