Created
July 3, 2016 14:43
-
-
Save bebo-dot-dev/380664afec598a9056cbd29e2bce4217 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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