简体   繁体   中英

Regex to replace string not in quotes in IntelliJ

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.

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 ( $ ).

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\""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM