Need help with Regular Expression to Match Blood Group

前端 未结 5 1137
不知归路
不知归路 2021-01-13 17:06

I\'m trying to come up with a regex that helps me validate a Blood Group field - which should accept only A[+-], B[+-], AB[+-] and O[+-].

Here\'s th

相关标签:
5条回答
  • 2021-01-13 17:29

    ^(A|B|AB|O)[+-]?$ This will produce the correct out put.

    0 讨论(0)
  • 2021-01-13 17:33

    For case insensitive within html pattern attribute you may try this

    ([AaBbOo]|[Aa][Bb])[\+-]
    
    
    <input type="text" maxlength="3" pattern="([AaBbOo]|[Aa][Bb])[\+-]" required />
    
    0 讨论(0)
  • 2021-01-13 17:41

    When you are building an alternation (e.g. (A|B|AB|O)), you should be careful with the ordering of the elements. Many regex engines will stop at the first alternate that matches (rather than the longest). If it weren't for the [-+] forcing a backtrack, (A|B|AB|O)[-+] would not work for "AB+". It is probably better to say (AB|A|B|O)[-+] (but you should check the docs for your regex engine).

    Also, if you do not intend to capture the antigen for latter use, you should you use the non-capturing grouping parentheses: (?:AB|A|B|O)[-+].

    Furthermore, if you want to ensure that the only thing in the string is a blood type then you need anchors to prevent it from matching only part of the string: ^(?:AB|A|B|O)[-+]$. A quick note on anchors, Depending on your regex engine, ^ may match the beginning of a line rather than the beginning of the string if you pass it a multiline-match option. Similarly, $ may match the end of a line rather than the end of a string. For this reason there are three other anchors in common (but not %100) usage: \A, \Z, and \z. If your regex engine supports them, \A always matches the start of the string, \Z matches the end of the string or a newline just before the end of the string, and \z matches only the send of the string.

    0 讨论(0)
  • 2021-01-13 17:48

    Try:

    (A|B|AB|O)[+-]
    

    Using square brackets defines a character class, which can only be a single character. The parentheses create a grouping which allows it to do what you want. You also don't need to escape the +- in the character class, as they don't have their regexy meaning inside of it.

    As you mentioned in the comments, if it is a string you want to match against that has the exact values you are looking for, you might want to do this:

    ^(A|B|AB|O)[+-]$
    

    Without the start of string and end of string anchors, things like "helloAB+asdads" would match.

    0 讨论(0)
  • 2021-01-13 17:51

    The brackets [] denote a character class, meaning "any of the characters herein". You want the parentheses () for grouping:

    (A|B|AB|0)(\+|-)
    
    0 讨论(0)
提交回复
热议问题