Skip to content

Instantly share code, notes, and snippets.

@bebo-dot-dev
Created July 3, 2016 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bebo-dot-dev/380664afec598a9056cbd29e2bce4217 to your computer and use it in GitHub Desktop.
Save bebo-dot-dev/380664afec598a9056cbd29e2bce4217 to your computer and use it in GitHub Desktop.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaRegexTest {
public static void main(String []args)
{
String textToSearch = "-DARDUINO_BOARD=\"ESP8266_ESP01\" -DDEFINE_NO_2=\"ESP8266_ESP01\" -DALREADY_ESCAPED=\\\"VALUE\\\" -DDEFINE_WITH_WHITESPACE=\"ESP8266 ESP01\"";
Pattern regex = Pattern.compile("-D\\S+=\"\\S+\""); //value contains any char but whitespace
Matcher regexMatcher = regex.matcher(textToSearch);
String replacedStr = textToSearch;
System.out.println("----------------------------------------------------------------------------------------------------------------");
System.out.println("No whitespace replacement");
System.out.println("----------------------------------------------------------------------------------------------------------------");
System.out.println("Original text: " + textToSearch);
while(regexMatcher.find()) {
System.out.println("Found value: " + regexMatcher.group(0));
String newstring = regexMatcher.group(0).replaceAll("\"","\\\\\"");
System.out.println("Escaped value: " + newstring);
replacedStr = replacedStr.replace(regexMatcher.group(0), newstring);
}
System.out.println("New text: " + replacedStr);
System.out.println("----------------------------------------------------------------------------------------------------------------");
System.out.println("With whitespace replacement");
System.out.println("----------------------------------------------------------------------------------------------------------------");
regex = Pattern.compile("-D\\S+=\".+?\""); //value contains any char including whitespace
regexMatcher = regex.matcher(textToSearch);
replacedStr = textToSearch;
System.out.println("Original text: " + textToSearch);
while(regexMatcher.find()) {
System.out.println("Found value: " + regexMatcher.group(0));
String newstring = regexMatcher.group(0).replaceAll("\"","\\\\\"");
System.out.println("Escaped value: " + newstring);
replacedStr = replacedStr.replace(regexMatcher.group(0), newstring);
}
System.out.println("New text: " + replacedStr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment