2017-07-31 43 views
2

使用正則表達式與String.matches我有一個String數組如何用Java

String[] arrayOfLine = { 
    "I.2 Other Interpretive Provisions", 
    "I.3 Accounting Terms", 
    "Including all", 
    "II.1 The Loans", 
    "II.3 Prepayments.", 
    "III.2 Illegality", 
    "IV.2 Conditions", 
    "V.2 Authorization", 
    "expected to have" 
}; 

我想只挑數組元素與roman.number即 開始I.2,II.1開始等等。

我想這一點,但它不工作

String regex = "\b[A-Z]+\\.[0-9]\b"; 
for (int i = 0; i < arrayOfLine.length; i++) { 
    if(arrayOfLine[i].matches(regex)){ 
     listOfHeadings.add(arrayOfLine[i]); 
    } 
} 
+1

'\ B'必須'\\ B'。另外,你需要使用'.find()'和'Matcher'對象。它看起來像你需要找到所有以該模式開始的項目。如果是,請使用'^ [A-Z] + \\。[0-9]' –

+2

'.matches'將嘗試匹配完整的輸入。使用:'「[A-Z] + \\。[0-9] \\ b。*」' – anubhava

+0

您給'arrayOfLine'的例子可以包含除你提到的值之外的值嗎? –

回答

5

它看起來像你需要找到與圖案開始的所有項目。使用"^[A-Z]+\\.[0-9]+\\b"模式並確保您運行Matcher對象的find()方法找到部分匹配字符串內部。 .matches()僅查找整個字符串匹配。請注意,\b字邊界必須在Java字符串文字內定義爲"\\b"

Java demo

String[] arrayOfLine = {"I.2 Other Interpretive Provisions" , "I.3 Accounting Terms","Including all","II.1 The Loans","II.3 Prepayments.","III.2 Illegality","IV.2 Conditions","V.2 Authorization","expected to have"}; 
Pattern pat = Pattern.compile("^[A-Z]+\\.[0-9]+\\b"); 
List<String> listOfHeadings = new ArrayList<>(); 
for (String s : arrayOfLine) { 
    Matcher m = pat.matcher(s); 
    if (m.find()) { 
     listOfHeadings.add(s); 
    } 
} 
System.out.println(listOfHeadings); 
+0

以外的值,如果我添加「2017」。 ,「。」 ,「$ 30」,「AVAILABLE」。「在arrayOfLine中,這些也是按模式拾取的。 – jagga

+0

@jagga:請給我看你的代碼。 [**我的解決方案找不到它們](https://ideone.com/u3mwj3)。 –

+0

是的,它是工作謝謝 – jagga

0

您嘗試前人的精力用PatternsMatchers。這是一個工作示例

Pattern pattern = Pattern.compile("[A-Z]+\\.[0-9]"); 
    for (int i = 0; i < arrayOfLine.length; i++) { 
     Matcher match = pattern.matcher(arrayOfLine[i]); 
     while (match.find()) { 
      listOfHeadings.add(match.group()); 
     } 
    } 
0

這裏是regex檢查羅馬數字與點是^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})[.]

import java.util.*; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
class test 
    { 
    public static void main(String[] args) { 
    String[] a = { 
    "I.2 Other Interpretive Provisions", 
    "I.3 Accounting Terms", 
    "Including all", 
    "II.1 The Loans", 
    "II.3 Prepayments.", 
    "III.2 Illegality", 
    "IV.2 Conditions", 
    "V.2 Authorization", 
    "expected to have" 
    }; 
    int i=0; 
    int b=a.length; 
    Pattern MY_PATTERN = Pattern.compile("^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})[.]"); 
    for(i=0;i<b;i++) 
    { 
     Matcher m = MY_PATTERN.matcher(a[i]); 
     if (m.find()) 
      System.out.println(a[i]); 
    } 
    } 
} 

輸出:

I.2 Other Interpretive Provisions 
I.3 Accounting Terms 
II.1 The Loans 
II.3 Prepayments. 
III.2 Illegality 
IV.2 Conditions 
V.2 Authorization