-2

I'm trying to write code which finds all words that are in the following format

"some text":

So alphanumeric characters which are within " symbols and which end with the : symbol. My goal once I find these is to remove the " character and wrap the entire string in tag. So after the code has run, the above text would look like this,

<strong>some text:</strong>

So I believe the regex to find such text for wrapping is the following (formatted for Java),

(\".*?\"):{1}

And by using the following code, I should be able to iterate through all the matches.

Pattern pattern = Pattern.compile("(\".*?\"):{1}");
Matcher matcher = pattern.matcher(stringToSearch);

while(matcher.find()) {
  String matchedGroup = matcher.group();
  matchedGroup = matchedGroup.replaceAll("\"", "");
  matchedGroup = "<strong>" + matchedGroup + "</strong>";
  
  // now what?
}

So I probably went about that all wrong.

Now that I've wrapped the word I wanted in a strong tag, how do I "put it back" where it was?

0

1 Answer 1

2

Assuming you expect your double quotes to always be balanced, you may just use String#replaceAll here for a more terse solution:

String input = "Here is \"some text\": and also \"some other text\":";
String output = input.replaceAll("\"(.*?)\":", "<strong>$1:</strong>");
System.out.println(output);

This prints:

Here is <strong>some text:</strong> and also <strong>some other text:</strong>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.