What regular expression can get a number sequence from the input string, contains backslashes and not a numbers, for example –
"12\34a56ss7890"
I need to –
1234567890
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The following example:
gives output:
where X is not a X but a little rectangle – a symbol which is shown when the text showing control does not know how to draw it, a so called non printable character.
It is because in String a the “\2” part obviously tries to be interpreted as a single escaped sign “\u0002”- similar to “\n” “\t” – you can see this in debugger (i tried it using NetBeans)
Since the first argument of a replaceAll method is passed to [Pattern.compile](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)) it needs to be escaped twice as opposed to String literal (like b).
So if the String “12\34a56ss7890” looks like this on screen you have printed it out like this:
which is solved in the second example.
However if the literal is given as “12\34a56ss7890” then I think you can’t handle it with a single regexp, because if the backslash is followed by a number it gets interpreted as as \u0000 -\u0009 so the best I can think of is a very ugly solution:
the first then replacements (\u0000-\u0009) might be rewritten as a for loop to make it look elegant.
+1 for an EXCELLENT question 🙂
EDIT:
actually if a backslash is followed by more than one number they all get interpreted as a single sign – up to three numbers after a backslash, the fourth number will be treated as a single number.
Therefore, my solution is not generally correct, but could be extended to be. I would recommend Robin’s solution below as it is far more efficient.