10

I have a string in Android. I would like to wrap all the instances of 4 or more continuous digits with some html. I imagine this will be done with regex, but I have a hard time getting even the most basic regular expressions to work.

Can someone help me with this?

I would like to change:

var input = "My phone is 1234567890 and my office is 7894561230";

To

var output = "My phone is <u>1234567890</u> and my office is <u>7894561230</u>";

1 Answer 1

40

This will do it:

String input = "My phone is 1234567890 and my office is 7894561230";
String regex = "\\d{4,}";
String output = input.replaceAll(regex, "<u>$0</u>");
System.out.println(output);
Sign up to request clarification or add additional context in comments.

3 Comments

Amazing, I didn't realize you can use $# with String.replaceAll. That makes life way easier. Thanks.
@Keppil, whats is this "\\d{4,}" . i want replace an <iframe src= with <a href= tag keeping the url same. how to get this done?
@RahmathullahMPulikkal: \\d{4,} means 4 or more numbers. There are many posts on SO on how to search and replace strings, you should be able to find one to help you rather quickly.

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.