Java模式匹配

时间:2010-09-27 06:09:12

标签: java pattern-matching quantifiers

我有一个很长的模板,我需要根据某些模式提取某些字符串。当我通过一些例子时,我发现在这种情况下使用量词是很好的。例如,以下是我的模板,我需要从中提取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)$endWhile开始提取整个文本。然后我需要处理$ variable的值。之后,我需要在$while$endWhile之间插入原始文字。 我有提取变量的逻辑。但我不确定如何在这里使用量词或模式匹配。 有人可以为我提供一个示例代码吗?任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

您可以在此处使用一个相当简单的基于正则表达式的解决方案,使用匹配器:

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

参考:

答案 1 :(得分: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;

     }

}