Awesome
Awesome

Reputation: 457

Regex to replace string with quotes

I need to replace quotes in following string.

String str = "This is 'test()ing' and test()ing'";

Final output should be "This is test()ing and test()ing'";

i.e replace only if it starts with 'test() and ends with '. Text in between remains the same.

This one is not working.

str = str.replaceAll("^('test())(.*)(')$", "test()$2");

Please suggest suitable regex for the same.

Upvotes: 2

Views: 1544

Answers (4)

Trinimon
Trinimon

Reputation: 13967

Make the middle part non greedy:

(')(.*?)(')

i.e.

str = str.replaceAll("(')(.*?)(')", "$2");

and if it should always start with test(), add

str = str.replaceAll("(')(test().*?)(')", "$2");

Check this example and this one.

Upvotes: 1

femtoRgon
femtoRgon

Reputation: 33351

Doesn't look like you actually want to have the ^ and $ anchors (start/end of line) in your regex.

Aside from that, it will consume more than you want. If you want the .* to stop at the earliest point it can continue, you should make it match reluctantly, like .*?.

So your regex would be:

('test\(\))(.*?)(')

Upvotes: 1

introex
introex

Reputation: 261

This regular expression will have the desired outcome:

    str = str.replaceAll("'test\\(\\)(.*?)'", "test()$1");

with .*? the string is matched lazily and doesn't match to the end of the whole string.

Upvotes: 5

anubhava
anubhava

Reputation: 786101

You can use:

str = str.replaceAll("'(test\\(\\)[^']*)'", "$1");

RegEx Demo

Upvotes: 1

Related Questions