0

Suppose I have the following string User 192.168.46.3 connected to this AP. I want to replace the IP address in there with <font color='red'>"+192.168.46.3+"</font> so that I can change it's color. What is the best way to achieve this?

TychoTheTaco
  • 664
  • 1
  • 7
  • 28

3 Answers3

1

If you do not care much about validating the IPs, a simple regex could do the trick.

Grab java.util.regex.Pattern and .Matcher and use something like

([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})

To replace the group you want to replace.

Like this:

final Pattern p = new Pattern("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})")
final Matcher m = p.match("User 192.168.46.3 connected to this AP")
final String s = m.replaceAll("<font color='red'>$1</font>")
Tim
  • 958
  • 7
  • 8
0

This is the full code based on Tim“s answer:

String input = "User 192.168.46.3 connected to this AP";
String regex = "([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})";
String output = input.replaceAll(regex, "<font color='red'>$0</font>");
System.out.println(output);
Tiago Luz
  • 129
  • 6
0

You can use the Pattern.java and Matcher.java classes to detect ip addresses in your string.

Take a look at the Pattern.java docs, there is an exemple on how to use both of them correctly. Then you can loop through your matcher results and apply a ForegroundColorSpan to each of them.

SpannableString spannable = new SpannableString(YOUR_STRING_CONTAINING_AN_IP_ADDRESS);
Pattern p = Pattern.compile(YOUR_REGEX);
Matcher m = p.matcher(YOUR_STRING_CONTAINING_AN_IP_ADDRESS);
while(m.find()) {
     spannable.setSpan(new ForegroundColorSpan(COLOR_YOUR_WANT), m.start(), m.end()-1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
}

then you can use the spannable to set the text of a text view for example.

Tristan
  • 326
  • 2
  • 8