简体   繁体   中英

Regex Pattern Format Validation

I need a RegEx pattern which will be sent by the client where the starting characters will be alphanumeric, the length of this starting String will be defined by the number after this String. This is followed by a special character which will always be a single character. This is again followed by a variable length string of alphanumeric characters.

I have come closest to the below String and formats.

[A-Za-z0-9]{4}-[A-Za-z0-9]{5}         - RegEx Input String

[A-Za-z0-9]{2}#[A-Za-z0-9]{6}         - RegEx Input String

[0-9]{3}#[0-9]{5}                     - RegEx Input String

[a-z]{5}#[a-z]{5}                     - RegEx Input String

[A-Z]{4}#[a-z]{4}                     - RegEx Input String

[\w]{\d{1,1}}(\S{1,1})[\w]{\d{1,1}}   - RegEx Format

Is the above pattern and format correct?

Can we validate the RegEx input string against the required RegEx format?

This is a web service which will have an input as [A-Za-z0-9]{4}-[A-Za-z0-9]{5}. I need two things here. First, how do I validate this input to see if it matches the format I want and the proceed. The format is the one I mentioned above as RegEx format.

This regular expression should match the subset of regular expressions you're interested in :

\[(?:[a-zA-Z0-9](?:-[a-zA-Z0-9])?)*\](?:\{\d\})?\S\[(?:[a-zA-Z0-9](?:-[a-zA-Z0-9])?)*\](?:\{\d\})?

Let's break it down :

  • it matches a line which contains in sequence a character class, an optional quantifier, a separator, a second character class and its second optional quantifier
  • the separator is any non-whitespace character, \\S (you might want to change that to something more specific, or which includes some whitespaces)
  • the optional quantifier is easy, it's a digit surrounded with literal curly brackets, the whole enclosed in an unbound group we use to make it optional : (?:\\{\\d\\})? . Note that this will not accept multiple digits length, so you might want to change the \\d to \\d+ , nor the more specific {m,n} range quantifier.
  • a character class is a sequence of 0 or more characters or character-ranges, enclosed in literal brackets.
  • a character is a letter or digit : [a-zA-Z0-9](?:-[a-zA-Z0-9])? when the unbounded group isn't matched
  • a character range is a character followed by the literal - followed by another character : [a-zA-Z0-9](?:-[a-zA-Z0-9])? when the unbounded group is matched

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