Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Regex in Java to pattern match?

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.

like image 908
PAujla03 Avatar asked Aug 05 '26 13:08

PAujla03


2 Answers

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();
}
like image 190
Bergi Avatar answered Aug 07 '26 02:08

Bergi


you can use a function like this, with two arguments, viz.,

  • origingalString the original string to check
  • searchString the string to be searched

the code exactly,

public boolean checkCompletelyExist(String origingalString,String searchString){ 
  boolean found = false; 
  String regex = ""; 
  try{ 
    for(int i = 0; i < searchString.length();i++){ 
      String temp = String.valueOf(searchString.charAt(i)); 
      regex = "[\\x20-\\x7E]*"+"["+temp.toLowerCase()+"|"+temp.toUpperCase()+"]+[\\x20-\\x7E]*"; 
      if(!origingalString.matches(regex)){ 
        found = true; 
        break; 
      } 
    } 
    System.out.println("other character present : "+found); 
  } catch (Exception e) { 
    e.printStackTrace(); 
  } 
  return found; 
}

eg:

checkCompletelyExist("MDCLXVIivxlcdm","XMLVID") output will be other character present : false

and

checkCompletelyExist("MDCLXVIivxlcdm","ABXMLVA") output will be other character present : true

like image 22
Arundev Avatar answered Aug 07 '26 02:08

Arundev