Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6173353
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T23:33:25+00:00 2026-05-23T23:33:25+00:00

I’m implementing a keyword highlighter in Java. I’m using java.util.regex.Pattern to highlight (making bold)

  • 0

I’m implementing a keyword highlighter in Java. I’m using java.util.regex.Pattern to highlight (making bold) keyword within String content. The following piece of code is working fine for alphanumeric keywords, but it is not working for some special characters. For example, in String content, I would like to highlight the keyword c++ which has the special character + (plus), but it’s not getting highlighted properly. How do I escape + character so that c++ is highlighted?

public static void main(String[] args)
{
    String content = "java,c++,ejb,struts,j2ee,hibernate";
    System.out.println("CONTENT: " + content);
    String highlight = "C++";

    System.out.println("HIGHLIGHT KEYWORD: " + highlight);

    //highlight = highlight.replaceAll(Pattern.quote("+"), "\\\\+");
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\b" + highlight + "\\b", java.util.regex.Pattern.CASE_INSENSITIVE);
    System.out.println("PATTERN: " + pattern.pattern());
    java.util.regex.Matcher matcher = pattern.matcher(content);

    while (matcher.find()) {
        System.out.println("Match found!!!");
        for (int i = 0; i <= matcher.groupCount(); i++) {
        System.out.println(matcher.group(i));
        content = matcher.replaceAll("<B>" + matcher.group(i) + "</B>");
        }
    }
    System.out.println("RESULT: " + content);
}

Output:
CONTENT: java,c++,ejb,struts,j2ee,hibernate
HIGHLIGHT KEYWORD: C++
PATTERN: \bC++\b
Match found!!!
c
RESULT: java,c++,ejb,struts,j2ee,hibernate


I even tried to escape ‘+’ before calling Pattern.compile like this,

highlight = highlight.replaceAll(Pattern.quote("+"), "\\\\+");

but still I’m not able to get the syntax right. Can somebody help me solve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T23:33:26+00:00Added an answer on May 23, 2026 at 11:33 pm

    This should do what you need:

    Pattern pattern = Pattern.compile(
        "\\b" 
        + Pattern.quote(highlight)
        + "\\b",
        Pattern.CASE_INSENSITIVE);
    

    Update: you are right, the above doesn’t work for C++ (\b matches word boundaries and doesn’t recognize ++ as a word). We need a more complicated solution:

    Pattern pattern = Pattern.compile(
        "\\b" 
        + Pattern.quote(highlight)
        + "(?![^\\p{Punct}\\s])", // matches if the match is not followed by
                                  // anything other than whitespace or punctuation
        Pattern.CASE_INSENSITIVE);
    

    Update in response to comments: it seems that you need more logic in your pattern creation. Here’s a helper method to create the pattern for you:

    private static final String WORD_BOUNDARY = "\\b";
    // edit this to suit your neds:
    private static final String ALLOWED = "[^,.!\\-\\s]";
    private static final String LOOKAHEAD = "(?!" + ALLOWED + ")";
    private static final String LOOKBEHIND = "(?<!" + ALLOWED + ")";
    
    public static Pattern createHighlightPattern(final String highlight) {
        final Pattern pattern = Pattern.compile(
                (Character.isLetterOrDigit(highlight.charAt(0)) 
                 ? WORD_BOUNDARY : LOOKBEHIND)
                + Pattern.quote(highlight)
                + (Character.isLetterOrDigit(highlight.charAt(highlight.length() - 1))
                 ? WORD_BOUNDARY : LOOKAHEAD),
                Pattern.CASE_INSENSITIVE);
        return pattern;
    }
    

    And here is some test code to check that it works:

    private static void testMatch(final String haystack, final String needle) {
        final Matcher matcher = createHighlightPattern(needle).matcher(haystack);
        if (!matcher.find())
            System.out.println("Failed to find pattern " + needle);
        while (matcher.find())
            System.out.println("Found additional match: " + matcher.group() +
                               " for pattern " + needle);
    }
    
    public static void main(final String[] args) {
        final String testString = "java,c++,hibernate,.net,asp.net,c#,spring";
        testMatch(testString, "java");
        testMatch(testString, "c++");
        testMatch(testString, ".net");
        testMatch(testString, "c#");
    }
    

    When I run this method, I don’t see any output (which is good :-))

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I've got a string that has curly quotes in it. I'd like to replace
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.