[英]How to use regex with String.matches in java
I have a String array 我有一个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"
};
I want to pick only those array elements which starts with roman.number ie starting with I.2, II.1 and so on. 我想只选择以roman.number开头的数组元素,即从I.2,II.1开始,依此类推。
I am trying this, but it is not working 我正在尝试这个,但它不起作用
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]);
}
}
It looks like you need to find all items that start with the pattern. 看起来你需要找到以模式开头的所有项目。 Use
"^[AZ]+\\\\.[0-9]+\\\\b"
pattern and make sure you run the find()
method of the Matcher
object to find partial matches inside strings. 使用
"^[AZ]+\\\\.[0-9]+\\\\b"
模式并确保运行Matcher
对象的find()
方法以查找字符串内的部分匹配。 .matches()
finds the entire string matches only. .matches()
查找整个字符串匹配项。 Note that \\b
word boundary must be defined as "\\\\b"
inside a Java string literal. 请注意,
\\b
字边界必须在Java字符串文字中定义为"\\\\b"
。
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);
You sould try using Patterns and Matchers . 你可以尝试使用模式和匹配器 。 Here is a working example
这是一个有效的例子
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());
}
}
Here is regex
for checking roman number with dot is ^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})[.]
. 这里是用于检查罗马数字的
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]);
}
}
}
Output: 输出:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.