views:

73

answers:

1

Hi All, I've a long template from which I need to extract certain strings based on certain patterns. When I went through some examples I found that use of quantifiers is good in such situations.For example following is my template, from which I need to extract while and doWhile.

This is a sample document.
$while($variable)This text can be repeated many times until do while is called.$endWhile.
Some sample text follows this.
$while($variable2)This text can be repeated many times until do while is called.$endWhile.
Some sample text.

I need to extract the whole text, starting from $while($variable) till $endWhile. I then need to process the value of $variable. After that I need to insert the text between $while and $endWhile to the original text. I've the logic of extracting the variable. But I'm not sure how to use quantifiers or pattern match here. Can someone please provide me a sample code for this? Any help will be greatly appreciated

+1  A: 

You can use a rather simple regex-based solution here with a Matcher:

Pattern pattern = Pattern.compile("\\$while\\((.*?)\\)(.*?)\\$endWhile", Pattern.DOTALL);
Matcher matcher = pattern.matcher(yourString);
while(matcher.find()){
    String variable = matcher.group(1); // this will include the $
    String value = matcher.group(2);
    // now do something with variable and value
}

If you want to replace the variables in the original text, you should use the Matcher.appendReplacement() / Matcher.appendTail() solution:

Pattern pattern = Pattern.compile("\\$while\\((.*?)\\)(.*?)\\$endWhile", Pattern.DOTALL);
Matcher matcher = pattern.matcher(yourString);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
    String variable = matcher.group(1); // this will include the $
    String value = matcher.group(2);
    // now do something with variable and value
    matcher.appendReplacement(sb, value);
}
matcher.appendTail(sb);

Reference:

seanizer