2

Hello guys I'm starting to learn regex and I want to replace some characters from string.

this is my test case:

Example string:

+52 924 340 2304

Expected output:

09243402304

This is what I've tried:

String number = cursor.getString(col_number).replace("\\d{2}", "");

But I can't seem to get my expected output. Any help? I would gladly appreciate your help. Thanks.

Update:

Also, I want to remove all whitespace characters from the string and I forgot to add if the string has other characters like (,),-

1
  • Don't use regex for this, you can simply cut the number using substring. Commented Sep 8, 2014 at 8:41

6 Answers 6

1

use this :

.replaceAll("^[^\\s]+|\\s", "")

demo here : http://regex101.com/r/uY9xB2/1

Sign up to request clarification or add additional context in comments.

2 Comments

thanks it works! But I have to change to: replaceAll("^[^\\s]+|\\s", "")
instead of negated character class, you could use ^\\S+
1

Your method:

.replace("\\d{2}", "");

will fail to work because in Java String#replace doesn't take a regex. Try String#replaceAll OR String#replaceFirst

You can use:

String number = cursor.getString(col_number).replace(" ", "").replaceFirst("\\+\\d{2}", "0");

1 Comment

I'm only getting 0. not my expected result.
1
String number = cursor.getString(col_number).replaceAll("^\\+\\d{2}", "0").replaceAll("[^\\d]", "")

1 Comment

@Cedy Lee, I suppose you want to remove everything that's not a digit? There's a way for that, see my updated answer
0

Why do you not split the String at the whitespaces. Then you replace the first entry with a 0, and concatenate the array parts to one String again. Done.

Comments

0

@anibhava already mentioned your problem, I want to suggest another solution, you can simply remove the white spaces and cut the string using String#substring:

number.replaceAll("\\s+", "").substring(3); //you might want to add the 0 using + operator

Comments

0
^\+\d{2}[^\d]*(\d+)[^\d]*(\d+)[^\d]*(\d+)$

You can use this and then replace with

 0$1$2$3

See demo.

http://regex101.com/r/iX5xR2/12

This will work for all cases

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.