2

I'm having an array of strings (phone numbers) and i need to remove +, which is in front of one of the elements (numbers) since it throws an NumberFormatException when i try to cast it to int.

The elements in array are 0888888888 0888123456 +359886001122 and i have already used .split(" ") in order to separate them. I've also tried .split(" +") in order to remove + from the last one, but this didn't work.

1
  • split(" +") won't work because + is a special regex character that needs to be escaped: split(" \\+") Commented Mar 15, 2017 at 11:11

3 Answers 3

9

You have to use replaceAll instead of split, for example :

"0888888888 0888123456 +359886001122".replaceAll("\\+", "");

this will show you :

0888888888 0888123456 359886001122
//-------------------^------------

Then if you want to split each number you can use split(" ") like this :

String numbers[] = "0888888888 0888123456 +359886001122".replaceAll("\\+", "").split(" ");
System.out.println(Arrays.toString(numbers));

this will give you :

[0888888888, 0888123456, 359886001122]

EDIT

Or like @shmosel said in comment you ca use replace("+", "")

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

7 Comments

Or just replace("+", "")
@shmosel without slash it throw an error Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
replace() doesn't use regex.
aaahhh, ok i get it @shmosel you are using replace, i use replaceAll for that i get this error, yes you are correct this can be done with replace("+", "")
No problem, I've been bitten a few times by this so I like to share this solution :D
|
0

You can replace it with

var lv_numbers = "0888888888 0888123456 +359886001122".replace('+','');

Comments

0

Split uses a regular expression, so you can define to include and optional '+' in the split matcher.

String [] result = "0888888888 0888123456 +359886001122".split("\\s[\\+]{0,1}");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.