3

How to replace a sub-string in java of form " :[number]: "

example:

string="Hello:6:World"

After replacement,

HelloWorld
8
  • 4
    What's wrong with :\\d+: ? Commented Nov 3, 2014 at 9:19
  • First remove the last character if you are sure that the last one is ':' and then simply use the split() method Commented Nov 3, 2014 at 9:22
  • I want a Regular Expression for this. @Reyjohn Commented Nov 3, 2014 at 9:29
  • 1
    provide your expected output Commented Nov 3, 2014 at 9:31
  • @KhaledSaif that's what i said 18 mins ago. Commented Nov 3, 2014 at 9:36

4 Answers 4

2
ss="hello:909:world"; 

do as below:

String value = ss.replaceAll("[:]*[0-9]*[:]*","");
Sign up to request clarification or add additional context in comments.

5 Comments

just :\\d*: would be enough.
* is for 0 or more characters if you want to ensure at least one character then use + instead of *
This regexp is not correct. It replaces single standing : and numbers without surrounded by :. It would Make "Hello 5 World" as well to "Hello World". So this is what the QE wants???
+ would mean that there has to be at least one : followed by at least one digit followed by at least one :
String value = ss.replaceAll(":[0-9]+:",""); would do what other commentators are saying.
2

You can use a regex to define your desired pattern

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...

1 Comment

did you check your pattern?
1

Do like this

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

Comments

0

Edit 1: After the question was changed, one should use

:\d+:

and within Java

:\\d+:

This is the answer for replacing :: as well.

This is the regexp you should use:

:\d*:

Regular expression visualization

Debuggex Demo

And here is a running JavaCode snipped:

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 is not modified.

2 Comments

since * matches zero repetitions as well though this will also match :: you should probably use :\d+: (one or more repetitions) depending on which is the desired behavior.
Strange. The question was edited. Before there was the sentence: "I want to replace :: as well. Hence I used *.

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.