我有一个String数组
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]);
}
}
答案 0 :(得分:6)
看起来您需要查找以该模式开头的所有项目。使用"^[A-Z]+\\.[0-9]+\\b"
模式并确保运行find()
对象的Matcher
方法,以在字符串内找到部分匹配项。 .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);
答案 1 :(得分:0)
您可以尝试使用Patterns和Matchers。这是一个工作示例
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());
}
}
答案 2 :(得分: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