How to replace substrings containing any integer in java?

How to replace a substring in java of the form ": [number]:"

example:

string="Hello:6:World"

      

After replacement

HelloWorld

      

+3


source to share


4 answers


ss="hello:909:world"; 

      

do the following:



String value = ss.replaceAll("[:]*[0-9]*[:]*","");

      

+2


source


You can use regex to define the pattern you want

String pattern = "(:\d+:)";
string EXAMPLE_TEST = ':12:'
System.out.println(EXAMPLE_TEST.replaceAll(pattern, "text to replace with"));

      



should work depending on what exactly you want to replace ...

+2


source


Do it like

String s = ":6:";     
s = s.replaceAll(":", "");

      

+1


source


Edit 1: After the question has been changed, one should use

:\d+:

      

and inside Java

:\\d+:

      

This is the answer to replacing :: .

This is the regex you should be using:

:\d*:

      

Regular expression visualization

Debuggex Demo

And here's the running JavaCode running:

String str = "Hello :4: World";
String s = str.replaceAll(":\\d*:","");
System.out.println(s);

      

One problem with replaceAll is often that the corrected string is returned . The string object from which replaceAll was called does not change.

0


source







All Articles