android - Java: Regex to extract all non numerals AND leading +, if any -


here's string method i'm using in java remove non-numerals given string:

replaceall("[^\\d.]", "") 

here's example of return:

original string: $%^&*+89896 89#6 new string: 89896896 

however, need retain leading '+' sign if 1 exists such in case of above illustration (thus, new string should +89896896). if php, have used preg function (^\+)|([\d]+) precisely results want. not sure how implement in java (android) though.

i came

replaceall("([^\+])([\d]+)", "") 

but results seem distorted. here's 1 test result:

original string: +u +00786uy769+&jh6ghj765765  new string: +007876765765  desired result: +007867696765765 

what doing wrong expression?

p.s. avoid using pattern , matcher classes unless way out.

use negative lookbehind based regex in string.replaceall function.

string.replaceall("(?<!^)\\+|[^\\d+]", ""); 

demo

if don't want remove dot add dot inside character class.

string.replaceall("(?<!^)\\+|[^\\d+.]", ""); 

(?<!^)\\+ match plus symbols except 1 @ start.


Comments