[英]Regular expression in java not working
I convert a excel file to a CSV , and that to a String. 我将excel文件转换为CSV,然后将其转换为字符串。
The problem is that a regular expression is not working correctly 问题是正则表达式无法正常工作
I want to detect this kind of text: 我想检测这种文本:
MYW Pkg, MYW Pkg + Quick Service Dining, MYW Pkg + Dining, MYW Pkg + Deluxe Dining,
MYW Pkg,MYW Pkg +快速服务用餐,MYW Pkg +用餐,MYW Pkg +豪华用餐,
Room + Tickets + Quick Service Dining
客房+门票+快速服务餐饮
I have an array of String. 我有一个字符串数组。 So I need to know a pattern for that, I try this but it doesn't detect it:
因此,我需要知道一种模式,可以尝试一下,但无法检测到它:
Pattern.compile("([A-Z]{3})+(\\s)+([A-Za-z]{3})+(\\s)+(\\+)");
I try to match "MYW Pkg +" for example, Do you know why it is not working? 我尝试匹配“ MYW Pkg +”,例如,您知道为什么它不起作用吗?
More code: 更多代码:
chain is the array with values like "MYW Pkg," 链是具有“ MYW Pkg”之类的值的数组,
Pattern patPackageDescription = Pattern.compile("([A-Z]{3})+(\\s)+([A-Za-z])+(\\s)+(\\+)");
for (int i = 0; i < chain.length; i++) {
Matcher matPackageDescription = patPackageDescription
.matcher(chain[i]);
if (matPackageDescription.matches()) {
String space = String.format("%1$-" + 50 + "s",
chain[i].toString());
a.append(space + "|\n");
}
}
Regards. 问候。
matches()
method tries to match the whole string against the pattern, to match a part of the string you need to use find()
method. matches()
方法尝试将整个字符串与模式进行匹配,以匹配一部分字符串,您需要使用find()
方法。
String str = "MYW Pkg, MYW Pkg + Quick Service Dining, MYW Pkg + Dining, MYW Pkg + Deluxe Dining,";
Pattern patPackageDescription = Pattern.compile("([A-Za-z]{3}\\s)+\\+");
Matcher matPackageDescription = patPackageDescription.matcher(str);
while (matPackageDescription.find()) {
System.out.println(matPackageDescription.group());
}
Outputs: 输出:
MYW Pkg +
MYW Pkg +
MYW Pkg +
Your problem is that you are using Matcher.matches()
which requires a full match, if you can either use find()
for partial matches or add .*
to match anything after your search string. 您的问题是您正在使用
Matcher.matches()
,如果您可以对部分匹配使用find()
或在搜索字符串后添加.*
来匹配任何内容,则需要完全匹配。
([A-Z]{3})+(\s)+([A-Za-z]{3})+(\s)+(\+).*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.