This question already has answers here:
Android: Coloring part of a string using TextView.setText()?
(15 answers)
Closed 6 years ago.
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?
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>")
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);
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.
Related
This question already has answers here:
Remove string after last occurrence of a character
(5 answers)
Closed 3 years ago.
I want to remove everything after last hyphen
branch:resource-fix-c95e12f
I have tried with following command :
replaceAll(".*[^/]*$","");
I want the expected result as branch:resource-fix
Instead of regex, could you use
String::lastIndexOf?
str.substring(0,str.lastIndexOf(‘-‘))
You can use this regex:
-[^-]+$
Example: https://regex101.com/r/dHSNNN/1
You can use the following pattern
-[^-]*$
Demo
This expression might simply work:
-[^-]*$
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "-[^-]*$";
final String string = "branch:resource-fix-c95e12f";
final String subst = "";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
Another option would be, ^(.*)-.*$ replaced with \\1.
Demo 2
The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
i am trying to split the string using regex with closing bracket as a delimiter and have to keep the bracket..
i/p String: (GROUP=test1)(GROUP=test2)(GROUP=test3)(GROUP=test4)
needed o/p:
(GROUP=test1)
(GROUP=test2)
(GROUP=test3)
(GROUP=test4)
I am using the java regex - "\([^)]*?\)" and it is throwing me the error..Below is the code I am using and when I try to get the group, its throwing the error..
Pattern splitDelRegex = Pattern.compile("\\([^)]*?\\)");
Matcher regexMatcher = splitDelRegex.matcher("(GROUP=test1)(GROUP=test2) (GROUP=test3)(GROUP=test4)");
List<String> matcherList = new ArrayList<String>();
while(regexMatcher.find()){
String perm = regexMatcher.group(1);
matcherList.add(perm);
}
any help is appreciated..Thanks
You simply forgot to put capturing parentheses around the entire regex. You are not capturing anything at all. Just change the regex to
Pattern splitDelRegex = Pattern.compile("(\\([^)]*?\\))");
^ ^
I tested this in Eclipse and got your desired output.
You could use
str.split(")")
That would return an array of strings which you would know are lacking the closing parentheses and so could add them back in afterwards. Thats seems much easier and less error prone to me.
You could try changing this line :
String perm = regexMatcher.group(1);
To this :
String perm = regexMatcher.group();
So you read the last found group.
I'm not sure why you need to split the string at all. You can capture each of the bracketed groups with a regex.
Try this regex (\\([a-zA-Z0-9=]*\\)). I have a capturing group () that looks for text that starts with a literal \\(, contains [a-zA-Z0-9=] zero or many times * and ends with a literal \\). This is a pretty loose regex, you could tighten up the match if the text inside the brackets will be predictable.
String input = "(GROUP=test1)(GROUP=test2)(GROUP=test3)(GROUP=test4)";
String regex = "(\\([a-zA-Z0-9=]*\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) { // find the next match
System.out.println(matcher.group()); // print the match
}
Output:
(GROUP=test1)
(GROUP=test2)
(GROUP=test3)
(GROUP=test4)
This question already has answers here:
Using Regular Expressions to Extract a Value in Java
(13 answers)
Closed 6 years ago.
I have a string like this:
"text1 <text2> text3"
I want to grab only the text in <>. So I need to get text2. How can I do it?
You can do it like this:
String value = "text1 <text2> text3 <text4>";
Pattern pattern = Pattern.compile("<([^>]*)>");
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output:
text2
text4
Response Update:
Assuming that you know that you have only one value to extract, Bohemian proposes a simpler approach, he proposes to proceed as next:
String value = "text1 <text2> text3";
String target = value.replaceAll(".*<(.*)>.*", "$1");
System.out.println(target);
Output:
text2
I suggest you to split this string using " " as a separator - you will get 3 -elements array and the second one is what you are looking for
This question already has answers here:
Java Regex matching between curly braces
(5 answers)
Closed 6 years ago.
I am trying to extract value between { } using
"\\(\\{[^}]+\\}\\)"
regex in java. My input is
String text = "Hi this is {text to be extracted}."
I want output as
"text to be extracted"
but that regex isn't working.
Try this:
"\\{([^}]*)\\}"
Online Demo
Then $1 is containing text to be extracted.
The regexp seems malformed.
You need to match extra characters before and after the group, and you do not need to escape the parenthesis.
Also, you can use the named group to extract exactly the text you care about
Here is working code
String text = "Hi this is {text to be extracted}.";
Pattern p = Pattern.compile(".*\\{(?<t>[^}]+)\\}.*");
Matcher m = p.matcher(text);
if (m.matches()) {
System.out.println(m.group("t"));
}
This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in quotes
(12 answers)
Closed 9 years ago.
I'm stuck with this regex.
So, I have input as:
"Crane device, (physical object)"(X1,x2,x4), not "Seen by research nurse (finding)", EntirePatellaBodyStructure(X1,X8), "Besnoitia wallacei (organism)", "Catatropis (organism)"(X1,x2,x4), not IntracerebralRouteQualifierValue, "Diospyros virginiana (organism)"(X1,x2,x4), not SuturingOfHandProcedure(X1)
and in the end I would like to get is:
"Crane device, (physical object)"(X1,x2,x4)
not "Seen by research nurse (finding)"
EntirePatellaBodyStructure(X1,X8)
"Besnoitia wallacei (organism)"
"Catatropis (organism)"(X1,x2,x4)
not IntracerebralRouteQualifierValue
"Diospyros virginiana (organism)"(X1,x2,x4)
not SuturingOfHandProcedure(X1)
I've tried regex
(\'[^\']*\')|(\"[^\"]*\")|([^,]+)|\\s*,\\s*
It works if I don't have a comma inside parentheses.
RegEx
(\w+\s)?("[^"]+"|\w+)(\(\w\d(,\w\d)*\))?
Java Code
String input = ... ;
Matcher m = Pattern.compile(
"(\\w+\\s)?(\"[^\"]+\"|\\w+)(\\(\\w\\d(,\\w\\d)*\\))?").matcher(input);
while(matcher.find()) {
System.out.println(matcher.group());
}
Output
"Crane device, (physical object)"(X1,x2,x4)
not "Seen by research nurse (finding)"
EntirePatellaBodyStructure(X1,X8)
not "Besnoitia wallacei (organism)"(X1,x2,x4)
not "Catatropis (organism)"(X1,x2,x4)
not IntracerebralRouteQualifierValue
not "Diospyros virginiana (organism)"(X1,x2,x4)
not SuturingOfHandProcedure(X1)
Don't use regexes for this. Write a simple parser that keeps track of the number of parentheses encountered, and whether or not you are inside quotes. For more information, see: RegEx match open tags except XHTML self-contained tags
Would this do what you need?
System.out.println(yourString.replaceAll(", not", "\nnot"));
Assuming that there is no possibility of nesting () within (), and no possibility of (say) \" within "", you can write something like:
private static final Pattern CUSTOM_SPLIT_PATTERN =
Pattern.compile("\\s*((?:\"[^\"]*\"|[(][^)]*[)]|[^\"(]+)+)");
private static final String[] customSplit(final String input) {
final List<String> ret = new ArrayList<String>();
final Matcher m = CUSTOM_SPLIT_PATTERN.matcher(input);
while(m.find()) {
ret.add(m.group(1));
}
return ret.toArray(new String[ret.size()]);
}
(disclaimer: not tested).