How to make a String include the ':' in between numbers only avoid the ':' before or after any character java?

Viewed 54

I want to make a String highlighted with the SpannableString java

I have the following string

    textString = "2021-01-26 19:23:18 Lat: 26.369919 Long: 83.46433";

From this, I am able to highlight the String using regex with decimal numbers from this

Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");

like this

textString = "2021-01-26 19:23:18 Lat: 26.369919 Long: 83.46433";

But now I want to make s String including the ':' in between numbers also and want to avoid the ':' before or after any nonnumeric character

I want to produce output like this

textString = "2021-01-26 19:23:18 Lat: 26.369919 Long: 83.46433";

2 Answers

Just include : in your character class inside the optional non-capture group and make non-capture group match 0 or more times:

\\d+(?:[:.]\\d+)*

RegEx Demo

Replacement would be:

"<b>$0</b>"

Note that this will match a number with multiple dots like 83.46433.135.

If you want to eliminate that then use:

\\d+(?:\\.\\d+|(?::\\d+)+)?

RegEx Demo 2

You could use Html#fromHtml here for a fairly straightforward approach:

String textString = "2021-01-26 19:23:18 Lat: 26.369919 Long: 83.46433";
textString = textString.replaceAll("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}:\\d{2}:\\d{2})", "<b>$1</b>-<b>$2</b>-<b>$3</b> <b>$4</b>");
textString = textString.replaceAll("(?<!\\S)(\\d+(?:\\.\\d+)?)(?!\\S)", "<b>$1</b>");
textView.setText(Html.fromHtml(textString));

If you were to log the value of textString after the regex replacement, you would see this value:

<b>2021</b>-<b>01</b>-<b>26</b> <b>19:23:18</b> Lat: <b>26.369919</b> Long: <b>83.46433</b>
Related