0

我有一个很长的模板,我需要根据某些模式从中提取某些字符串。当我浏览一些示例时,我发现在这种情况下使用量词很好。例如以下是我的模板,我需要从中提取whiledoWhile.

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.

我需要提取整个文本,从$while($variable)until开始$endWhile。然后我需要处理 $variable 的值。之后,我需要在原始文本之间插入文本$while$endWhile我有提取变量的逻辑。但我不确定如何在这里使用量词或模式匹配。有人可以为此提供一个示例代码吗?任何帮助将不胜感激

4

2 回答 2

3

您可以在此处使用一个相当简单的基于正则表达式的解决方案和 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
}

如果要替换原文中的变量,应该使用Matcher.appendReplacement() / Matcher.appendTail()解决方案:

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);

参考:

于 2010-09-27T07:00:40.497 回答
0

公共类 PatternInString {

static String testcase1 = "what i meant here";
static String testcase2 = "here";

public static void main(String args[])throws StringIndexOutOfBoundsException{
    PatternInString testInstance= new PatternInString();
    boolean result = testInstance.occurs(testcase1,testcase2);
    System.out.println(result);
}

//write your code here
public boolean occurs(String str1, String str2)throws StringIndexOutOfBoundsException
    { int i;
      boolean result=false;


      int num7=str1.indexOf(" ");
      int num8=str1.lastIndexOf(" ");
      String str6=str1.substring(num8+1);
      String str5=str1.substring(0,num7);
      if(str5.equals(str2))
      {
          result=true;
      }
      else if(str6.equals(str2))
      {
          result=true;
      }

     int num=-1;
      try
      {
      for(i=0;i<str1.length()-1;i++)
      {    num=num+1;
           num=str1.indexOf(" ",num);

           int num1=str1.indexOf(" ",num+1);
           String str=str1.substring(num+1,num1);

           if(str.equals(str2))
           {
               result=true;
               break;
           }



      }
      }
      catch(Exception e)
      {

      }


     return result;

     }

}

于 2013-08-10T17:09:27.377 回答