Search code examples
javaregexstringsplitspecial-characters

Is there any regex available to find only escape characters in a string in java?


I want to filter out the escape characters from the list of special characters.

String data = "21.LRK.31";
char[] charactersInData = data.toCharArray();
Pattern pattern = Pattern.compile("[^0-9^a-z^A-Z]+");
String specialCharacterInData = "";
String escapeCharacterInData = "";
for (int i = 0; i < charactersInData.length; i++) {
    Matcher matcher = pattern.matcher(String.valueOf(charactersInData[i]));
    if (matcher.matches()) {
        specialCharacterInData = String.valueOf(charactersInData[i]);
        break;
    }
}
pattern = Pattern.compile("[^0-9^a-z^A-Z]+");
if (specialCharacterInData.equals(".")) {
    escapeCharacterInData = "\\" + specialCharacterInData;
} else {
    escapeCharacterInData = specialCharacterInData;
}
String[] contentOfLicencePlateNumber = data.split(escapeCharacterInData);

Here after getting the specialCharacterInData I want to again check whether this special character is an escape character because to split a string by an escape character you need to add 2 backslashes (\\) before that.


Solution

  • If you want to split a string on any non alphanumeric characters, then it easy enough to do this with a one-liner:

    String data = "21.LRK.31";
    String[] parts = data.split("[^A-Za-z0-9]");
    

    Demo

    If you have needs beyond this, then update your question. I suspect you may be doing extra work which isn't necessary to achieve your final goal.

    Edit: If you really have a need to escape on a single unknown character, then consider just putting it into a character class. For example:

    System.out.println("Hello.World!".split("[.]")[1]);
    

    This will output World!, and we can split on dot, a metacharacter, without having to worry about escaping.