2015-04-16 27 views
-2
if (txt.matches("Who is the(.*)")) { 
     String re1=".*?"; 
     String re2="(?:[a-z][a-z]+)"; 
     String re3=".*?"; 
     String re4="(?:[a-z][a-z]+)"; 
     String re5=".*?"; 
     String re6="(?:[a-z][a-z]+)"; 
     String re7=".*?"; 
     String re8="((?:[a-z][a-z]+))"; 
     String re9=".*?"; 
     String re10="(?:[a-z][a-z]+)"; 
     String re11=".*?"; 
     String re12="((?:[a-z][a-z]+))"; 

     Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10+re11+re12,Pattern.CASE_INSENSITIVE | Pattern.DOTALL); 
     Matcher m = p.matcher(txt); 
     if (m.find()) 
     { 
      String word1=m.group(1); 
      String word2=m.group(2); 
      String z=word2.toString()+"&&"+word1.toString(); 
      System.out.println(z); 
    } 
    } 

我從網上獲得了該代碼,但並不理解代碼如何從字符串「txt」中提取少數所需單詞。特別是這個re1和re2是什麼......等等。對於任何東西 - 「誰是ECE的HOD」,它返回ECE & & HOD。有人可以請解釋代碼...請幫助。使用正則表達式從字符串中提取所需單詞

回答

0

查看代碼中的註釋以解釋此代碼的功能。所有re1re2正在創建一個字符串,然後將其加入代碼的Patern.compile()部分。如果您有2個字符串,如String foo = "foo"String bar = "bar",並且您的輸入爲String foobar = foo + bar;,則輸出爲foobar

//If the String object "txt" matches the given regex, which in this case is "Who is the(.*)" 
    if (txt.matches("Who is the(.*)")) { 
     String re1=".*?"; 
     String re2="(?:[a-z][a-z]+)"; 
     String re3=".*?"; 
     String re4="(?:[a-z][a-z]+)"; 
     String re5=".*?"; 
     String re6="(?:[a-z][a-z]+)"; 
     String re7=".*?"; 
     String re8="((?:[a-z][a-z]+))"; 
     String re9=".*?"; 
     String re10="(?:[a-z][a-z]+)"; 
     String re11=".*?"; 
     String re12="((?:[a-z][a-z]+))"; 


     //this creates a pattern using the above strings. 
     Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10+re11+re12,Pattern.CASE_INSENSITIVE | Pattern.DOTALL); 

     //creates matcher object from the String object "txt" 
     Matcher m = p.matcher(txt); 

     //m.find() "Attempts to find the next subsequence of the input sequence that matches the pattern.", if it does... 
     if (m.find()) 
     { 
      //m.group "Returns the input subsequence matched by the previous match." 
      String word1=m.group(1); 
      String word2=m.group(2); 
      //creates a string 
      String z=word2.toString()+"&&"+word1.toString(); 
      //prints out string 
      System.out.println(z); 
    } 
    } 

Source for quotes

+0

請你能說他們是如何匹配像什麼模式「 *?」在re1和「(?:[a-z] [a-z] +)」中,以及如何知道應該重複多少次,例如從re1到re12重複獲取所需的單詞。請解釋 –

+0

這是一個基本的正則表達式值:http://www.regexr.com/ – BlackHatSamurai

+0

謝謝你的幫助! –

相關問題