How to replace words outside of quotes

I would like to replace strings outside the quotes using str.replaceAll in Java, but leave the words in quotes intact

If I replaced Apple Pie:

Login: Apple "Apple Apple Apple"
Desired result: pie "Apple Apple Apple"

Note that the words inside the quotes were untouched

How to do it? All help appreciated!

+6
source share
5 answers

Search for Apple using lookaheads to make sure it's not surrounded by quotation marks:

 (?=(([^"]*"){2})*[^"]*$)Apple 

And replace with:

 Pie 

RegEx Demo


Update:

Based on the comments below you can use:

Code:

 String str = "Apple \"Apple\""; String repl = str.replaceAll("(?=(([^\"]*\"){2})*[^\"]*$)Apple", "Pie"); //=> Pie "Apple" "Another Apple Apple Apple" Pie 
+5
source

I assume this is what you want:

 String str = "Apple \"Apple\""; String replace = str.replaceAll("(?<!\")Apple(?!\")", "Pie"); 

Here is the work: https://regex101.com/r/kP0oV1/2

0
source

This works for your test:

 package mavensandbox; import static junit.framework.TestCase.assertEquals; public class Test { @org.junit.Test public void testName() throws Exception { String input = "Apple(\"Apple\")"; String output = replaceThoseWithoutQuotes("Apple", "Pie", input); assertEquals("Pie(\"Apple\")", output); } private String replaceThoseWithoutQuotes(String replace, String with, String input) { return input.replaceAll("(?<!\")" + replace + "(?!\")", with); } } 

I use what is called a negative lookahead and a negative lookbehind . He finds matches that do not have "front or back". Does this work for you?

0
source

Try matching the word with a space after it.

/ Apple \ s /

Then replace Pie with the same space after it.

0
source

It is also possible to do this without a more complex regular expression if you are looking for a more iterative solution, if you are so prone. You can divide by " and replace even-numbered indexes, and then rearrange the row.

  String input = "\"unique\" unique unique \"unique\" \"unique\" \"unique\" \"unique\" unique \"unique unique\" unique unique \""; System.out.println(input); String[] split = input.split("\""); for (int i = 0; i < split.length; i = i + 2) { split[i] = split[i].replaceAll("unique", "potato"); } String output = ""; for (String s : split) { output += s + "\""; } System.out.println(output); 

Output:

 "unique" unique unique "unique" "unique" "unique" "unique" unique "unique unique" unique unique " "unique" potato potato "unique" "unique" "unique" "unique" potato "unique unique" potato potato " 
0
source

Source: https://habr.com/ru/post/983120/


All Articles