Reputation: 488
I convert a excel file to a CSV , and that to a String.
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,
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?
More code:
chain is the array with values like "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.
Upvotes: 5
Views: 17461
Reputation: 13222
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.
([A-Z]{3})+(\s)+([A-Za-z]{3})+(\s)+(\+).*
Upvotes: 2
Reputation: 3415
matches()
method tries to match the whole string against the pattern, to match a part of the string you need to use find()
method.
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 +
Look here for an explanation.
Upvotes: 11