Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid escape sequence for Regular Expression

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )

public static final boolean isValidPhoneNumber(CharSequence target) {

    if (target == null || TextUtils.isEmpty(target)) {
        Pattern numberPattern = Pattern.compile("^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1})?([0-9]{10})$");
        Matcher numberMatcher = numberPattern.matcher(target);
        return numberMatcher.matches();
    }

    return false;
}

I used a regular expression checked online was working fine but not working on my android application. Plz help...

like image 893
Krishnakant Dalal Avatar asked Feb 24 '26 01:02

Krishnakant Dalal


1 Answers

Your backslashes need to be escaped --

Pattern numberPattern = Pattern.compile("^((\\+){0,1}91(\\s){0,1}(\\-){0,1}(\\s){0,1})?([0-9]{10})$");

this is because Java using the \ character as an escape character, to tell it you really mean \ and not an escape character, you have to write \\.

like image 146
iagreen Avatar answered Feb 25 '26 14:02

iagreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!