2010-09-27 188 views
0

我有一個很長的模板,我需要從某些模式中提取某些字符串。當我通過一些例子時,我發現在這種情況下量詞的使用很好。例如,以下是我的模板,我需要從中抽取whiledoWhileJava模式匹配

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之間的文本。 我有提取變量的邏輯。但我不確定如何在這裏使用量詞或模式匹配。 有人可以爲我提供一個示例代碼嗎?任何幫助將不勝感激

回答

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

參考:

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; 

    } 

}