简体   繁体   English

正则表达式替换IntelliJ中引号不是的字符串

[英]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 请参阅以下内容: 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 ( $ ). 这将确保字符串以action:开头action: via ^ ),以及any word-character, period, or dash直到字符串结尾( $ )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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