Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight a word based on search pattern in a string content

Tags:

java

regex

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.

like image 584
Anil Dasari Avatar asked Dec 06 '25 05:12

Anil Dasari


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!