简体   繁体   中英

Regex Expressions in Java

This is my first time using Regex and I'm finding some difficulties in validating a string against a regular expression of the sort (x,y,z)(y,z)(x,w) etc. This is the pattern that I have been trying to match with the string

    String expressionmatcher = "[\\([[wxyz][,]]*[wxyz]{1,1}\\)]*";
    boolean checker = expression.matches(expressionmatcher);    

    if (checker == true) {
        System.out.println("Expression Valid");
    }
    else
    {
        System.out.println("Expression is not valid");
    }

Although my pattern is accepted, the matcher also accepts everything that is included in the string regardless of the sequence. For example if I input 'x' or a '(' or a ',', it is accepted as a valid expression.

What should I do to fix this? Thank you

That's because the square brackets you have surrounding the entire thing indicate "one of the contents" -- so that if something matches any one of the inside groups, it'll work.

Easy fix is to replace the outer brackets with parentheses. And the brackets surrounding [wxyz][,] too, because if you replace the outer brackets without also replacing the brackets I just mentioned (,x) will also work. I believe you might also want to put a set of brackets around the outer parentheses followed by a + too -- this way you'll only match if you have at least one ordered something inside.

Few other improvements:

  • You don't need to have the parentheses in a pair of brackets
  • You don't need to say {1, 1} -- {1} works just fine
  • I'd recommend putting \\\\s* after the comma so you can put spaces (or any form of whitespace, for that matter) after the comma

This likely is not the most efficient regex you can get, as I'm not too experienced with them. It works, though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM