DaveB
DaveB

Reputation: 3083

Java Regex Everything Before and Including Match

I need the regex expression to remove any text before a match and including the match

eg. I want to remove "123S" and everything before it, I know I can do this with

    string.replaceAll("^.*?(?=[123S])","");
    string.replaceAll("123S","");

But really want to do it in a single expression (can't find another example anywhere!)

Upvotes: 2

Views: 665

Answers (4)

Thomas
Thomas

Reputation: 88707

You don't need the look ahead:

"abc123Sdef123Sxyz".replaceAll("^.*?123S",""); 

This replaces the first occurence only, if that is what you need (output is def123Sxyz).

In case you want to replace up to the last 123S, just remove the ? modifier:

"abc123Sdef123Sxyz".replaceAll("^.*123S","");

Output is xyz.

Upvotes: 4

James Clark
James Clark

Reputation: 1811

string.replaceAll("^.*?123S", "");

(?= is the "if followed by" pattern which you don't want, and [123S] isn't even correct it'll catch just '2' for instance.

Upvotes: 2

hsz
hsz

Reputation: 152206

You can do it with:

string.replaceAll("^.*123S","");

Remove non-greedy ? to match last occurence and .* everything before.

Upvotes: 4

Austin Heerwagen
Austin Heerwagen

Reputation: 663

string.replaceAll("^.*?123S","");

More efficient and improves clarity so someone else knows what you're doing.

Upvotes: 0

Related Questions