2014-04-10 18 views
0

我想找到名稱char的序列,例如
正則表達式來找到持續的圖案超過兩次或多次

  • AAA BBB或ZZZ(如RAAAJ,ABBBAAS)的名稱

  • ABABAB或CPCPCP

是否可以通過正則表達式找到?

我已經試過這

\\b\\w*?(\\w{2})\\w*?\\1\\w*?\\b on <b>'tatarak'</b> 

這個發現TA字應該發現,只有當TA是三次或在相同的多個

+0

如果插入'\\ W *?'在你希望怎麼回事它的工作之間? – devnull

+1

我很確定有一個重複... – HamZa

+1

@HamZa幾乎所有的正則表達式問題都有重複。 – devnull

回答

0

嘗試使用組和反向引用Pattern。評論

String[] namesWithRepeatedOneLetter = { "RAAAJ", "ABBBAAS" }; 
String[] namesWithRepeatedTwoLetters = { "ABABABC", "FOOBCBCD"}; 
//       | This is a posix character class, basically your a-zA-Z 
//       | range. Note the parenthesis which define it as a group. 
//       |   | This is a reference to previously declared 
//       |   | group (as group 1) 
//       |   | | Greedy quantifier for more than 2 
//       |   | | letter repeat 
Pattern p0 = Pattern.compile("(\\p{Alpha})\\1{2,}"); 
//          | Greedy quantifier for 2+ repeats (so 
//          | repetition is considered as such with 2 
//          | letter groups 
Pattern p1 = Pattern.compile("(\\p{Alpha}{2,})\\1{2,}"); 
for (String n : namesWithRepeatedOneLetter) { 
    Matcher m = p0.matcher(n); 
    while (m.find()) { 
     System.out.println(m.group()); 
    } 
} 
System.out.println(); 
for (String n: namesWithRepeatedTwoLetters) { 
    Matcher m = p1.matcher(n); 
    while (m.find()) { 
     System.out.println(m.group()); 
    } 
} 

輸出

AAA 
BBB 

ABABAB 

編輯要引用印地文字符,使用Unicode塊或腳本引用,而不是一個類或Posix的類。

例如:

Pattern p0 = Pattern.compile("(\\p{IsDevanagari})\\1{2,}"); 

最後,經過反向引用編輯量詞(貪婪+,現在貪婪{2,}),以便只有三次重複匹配。

+0

謝謝先生,這是我想要的,但我只想要那些重複三次或更多**想排除兩次** –

+0

@AlokTiwari不用客氣。將更新答案三次/印地文。儘管如此,請更新您的問題。 – Mena

+0

真棒先生,謝謝 –

0

這是怎麼回事?對於tatarak loremipsrecdks RAAAJ , ABBBAAS輸出

tata 
AAA 
BBB 
AA 

代碼

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class DublicatePattern { 


    public static void main(String[] args) { 
     String value = "tatarak loremipsrecdks RAAAJ , ABBBAAS"; 
     Pattern p = Pattern.compile("(\\w+)\\1+"); 
     Matcher m = p.matcher(value); 
     while (m.find()) { 
      System.out.println("Found: " + value.substring(m.start(), m.end())); 
     } 
    } 
}