i am trying to write a sample java program using regular expression which highlights a word in a string content based on given pattern. i tried following code. but no luck
Pattern pattern = Pattern.compile(".*(test).*", Pattern.CASE_INSENSITIVE);
String replaceAll = pattern.matcher(str).replaceAll("<span>$1</span>");
Ex 1:
input content : i am testing a program
input pattern : test*
expected : i am <span>testing<span> a program
Ex 2 :
input content : i am testing a program
input pattern : test
expected : i am <span>test<span>ing a program
Thanks in advance.
Try this.
String input = "i am testing a program";
System.out.println(input.replaceAll("(?i)test\\S*", "<span>$0</span>"));
// -> i am <span>testing</span> a program
System.out.println(input.replaceAll("(?i)test", "<span>$0</span>"));
// -> i am <span>test</span>ing a program
(?i) means CASE_INSENSITIVE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With