1

I have a text file that's marked up like this:

Old McDonald had a <:farm/101:>

When the program reading through this text file hits this tag, it passes farm/101 to a method that converts the tag to appropriate HTML code, depending on what sort of tag is passed. In this case, the word farm needs to be turned into a hyperlink, with 101 as its HREF. This is done in the parseTag() method, which is called as follows:

Pattern pattern = Pattern.compile("<:(.+?):>");        
Matcher tagMatch = pattern.matcher(in);

while (tagMatch.find()) {
    String parsed = parseTag(tagMatch.group(1);
    // replace tagMatch.group(0) with parsed
}

I then want to replace the entire tag with the output of that method. I've thought about doing something like:

Pattern pattern = Pattern.compile("<:");    
String split = pattern.split(in);    
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++){
    if (i%2 == 0) sb.append(split[i]);
    else sb.append(parseTag(split[i]);
} 
String final = sb.toString();

final here would give me what I want, but this seems messy..

1 Answer 1

3

You can use appendReplacement and appendTail methods from Matcher instance.

Try

StringBuffer sb= new StringBuffer();
while (tagMatch.find()) {
    //this will add text to buffer with replaced matched part
    tagMatch.appendReplacement(sb, parseTag(tagMatch.group(1)));
}
tagMatch.appendTail(sb);//to add rest of input after last replacement

String result = sb.toString();
System.out.println(result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.