I have read the documentation and various tutorials online but I'm still confused on how regex works in Java. What I am trying to do is create a function which takes in argument of type string. I then want to check if the passed string contains any characters other than MDCLXVIivxlcdm. So for example, string "XMLVID" should return false and "ABXMLVA" should return true.
public boolean checkString(String arg)
{
Pattern p = Pattern.complile("[a-zA-z]&&[^MDCLXVIivxlcdm]");
Matcher m = p.matcher(arg);
if(m.matches())
return true;
else
return false;
}
When I pass, "XMLIVD", "ABXMLVA", and "XMLABCIX", all return false. What am I doing wrong? Any help will be greatly appreciated.
You will need to use Java's character class intersection operator inside a character class, otherwise it literally matches &&
. Btw, your first character class from A
to (lowercase) z
also includes [\]^_
, which you certainly do not want; and you misspelled "Patter.complile".
Also, matches()
Attempts to match the entire region against the pattern.
So you either need to use find()
instead or pad the expression with .*
.
public boolean checkString(String arg) {
return Pattern.compile("[[a-zA-Z]&&[^MDCLXVIivxlcdm]]").matcher(arg).find();
}