Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Two Regular Expressions in one

 
Peter Heide
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regular Expressions can be used to validate if a String is in a valid format.

The following code checks if a string is valid using the following two rules

  • Starts with a letter from A to Z
  • Afterwards exactly 6 digits


  • Examples: A123456 is correct, A12345 is incorrect, AA is incorect

    The Java code is as follows:



    Result Output:

    ID A123456 is true
    ID A1 is false
    ID AA is false

    The problem is that a new rule comes into play:

    An ID is not valid when it starts with A33

    How can I code the first two rules and the new one together in one regular expression?
     
    Anubhav Anand
    Ranch Hand
    Posts: 341
    Firefox Browser Java Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Try this



    Visit this link. It has wonderful explanations.

    [Included the regex article url]
    [ April 03, 2008: Message edited by: Anubhav Anand ]
     
    Jim Yingst
    Wanderer
    Sheriff
    Posts: 18671
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    First a minor note - using lookingAt() is sort of an odd choice here, considering that you're also using \\z to force a match with the end of the pattern. It seems simpler to just use matches(), which requires a match of the entire expression, starting at the beginning and ending at, well, the end. Then you don't need to specify //z in the expression; it's implicit.

    Anyway, to add your new rule to the regex, you can use negative lookahead:

    Basically the (?!A33) means from this position (the beginning, in this case) the matcher needs to be able to scan ahead and not see A33. Then when it gets to the ), the pattern can forget about the lookahead expression and remember it's still at the beginning of the expression, and try to match the remainder of the pattern (the A-Z]{1}[0-9]{6}).
     
    Peter Heide
    Ranch Hand
    Posts: 31
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You solved the problem and also your advice to improve my code worked. Thank you very much Anubhav and Jim!
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic