2014-12-22 33 views
0

請參考下面的代碼如何找到在Java中使用模式的字符串

String line = "abc_dfgb_tf"; 

    String pattern1 = "(\\w+)([+-])(\\d+)(\\w+)"; 
    Pattern r1 = Pattern.compile(pattern1); 
    Matcher m1 = r1.matcher(line); 

    if (m1.find()) 
    { 
     System.out.println("Found value: " + m1.group(1)); 
     System.out.println("Found value: " + m1.group(2)); 
     System.out.println("Found value: " + m1.group(3)); 
     System.out.println("Found value: " + m1.group(4)); 
    } 

在「abc_dfgb_tf」串m1.find的情況下()來了假。

請建議將使用兩種類型的字符串 「abc_dfgb_tf」 和 「abc_dfgb_tf + 1cbv」

幫助

+1

只是做了'[+ - ]'部分可選:'[+ - ] ?'。 – Keppil

回答

2

您似乎想要選擇除第一組以外的所有內容。像

String line = "abc_dfgb_tf"; 
String pattern1 = "(\\w+)([+-]*)(\\d*)(\\w*)"; 
Pattern r1 = Pattern.compile(pattern1); 
Matcher m1 = r1.matcher(line); 

if (m1.find()) { 
    System.out.println("Found value: " + m1.group(1)); 
    System.out.println("Found value: " + m1.group(2)); 
    System.out.println("Found value: " + m1.group(3)); 
    System.out.println("Found value: " + m1.group(4)); 
} 

輸出的東西是

Found value: abc_dfgb_tf 
Found value: 
Found value: 
Found value: 

,如果我改變行String line = "abc_dfgb_tf+1cbv";輸出

Found value: abc_dfgb_tf 
Found value: + 
Found value: 1 
Found value: cbv 
+1

明白了.. Thnaks :) Elliott Frisch – vijendra

5

的你似乎想是這樣的模式:

String pattern1 = "(\\w+)(?:([+-])(\\d+)(\\w+))?"; 

那使可選尾部實際上是可選的。

+0

明白了.. Thnaks :) John Bollinger – vijendra

相關問題