giampaolo
giampaolo

Reputation: 6934

Regular expression for repeating text in test string

I'm trying to replace some code into another with regular expressions. I'm using Java but I think it's not relevant for the question

String testString = "sb.Append(\"first string to append(1) \");  sb.Append(\"second string to append(2)\");";
Pattern appendPattern = Pattern.compile("\\s*(\\w+)\\.Append\\((.*)\\);");
Matcher appendMatcher = appendPattern.matcher(testString);
System.out.println(appendMatcher.replaceAll("[$1 appendString: $2];"));

my expected result is:

[sb appendString: "first string to append(1) "];  [sb appendString: "second string to append(2)"];

what I got is:

[sb appendString "first string to append(1) ");  sb.Append("second string to append(2)"];

it's something .* has precedence over \\) when deciding where match ends. Where am I wrong?

Upvotes: 0

Views: 51

Answers (2)

hwnd
hwnd

Reputation: 70732

Greedy will consume as much as possible. Follow .* with ? for a non-greedy match.

\\s*(\\w+)\\.Append\\((.*?)\\);

Working demo

Upvotes: 2

aelor
aelor

Reputation: 11116

use this:

\s*(\w+)\.Append\((.*?)\);

make it lazy along with the global modifier

demo here : http://regex101.com/r/vV0tN6

Upvotes: 2

Related Questions