Reputation: 2456
I'm not very good at regex stuff, but what I'm trying to do is replace anything that matches
action: something
where the something is not inside of either single or double quotes.
I want to replace this with action: "something".
So, it should not replace action: "something" or action: 'something' since those already contain quotes. The something could be any word, so it's not static. The action: piece will always be static.
Upvotes: 1
Views: 2274
Reputation: 72855
Use capture groups to accomplish this:
action: (\w+)
And replace with:
action: "$1"
See it in action: http://regex101.com/r/sP4pP7
action: something
//becomes
action: "something"
Obviously if you want something more sophisticated (non-word characters) it changes. You could use something like this:
^action: ([.-\w]+)$
Which will ensure the string begins with action:
(via ^
), and any word-character, period, or dash
until the end of the string ($
).
Upvotes: 7
Reputation: 952
you can use backreference
Pattern PATT = Pattern.compile("action:(\\w+)");
System.out.println(PATT.matcher("test action:word").replaceFirst("action:\"$1\""));
System.out.println(PATT.matcher(" bla action:\"quoted\" bla").replaceFirst("action:\"$1\""));
Upvotes: 0