0

特定のパターンに基づいて特定の文字列を抽出する必要がある長いテンプレートがあります。いくつかの例を見てみると、そのような状況では数量詞の使用が適切であることがわかりました。たとえば、以下は私のテンプレートであり、そこから抽出する必要がwhileあり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.

$while($variable)から始めて、テキスト全体を抽出する必要があります$endWhile。次に、$variableの値を処理する必要があります。その後、元のテキストの間にテキストを挿入する必要があり$whileます$endWhile。変数を抽出するロジックがあります。しかし、ここで数量詞またはパターンマッチを使用する方法がわかりません。誰かが私にこれのサンプルコードを提供してもらえますか?どんな助けでも大歓迎です

4

2 に答える 2

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

参照:

于 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 に答える