Regex for string optionally divided by one white space

I'm new to angular / javascript and am in need of a regex that should allow one line two lines with a space if needed. Maximum 10 characters.

Valid strings: "ASDF" "asdf asdf"

I've tried similarly: ^ [[az] {1,10}? [az] {2.9}] {1.10}? $ but can't get it to work

+3


source to share


2 answers


Quanters only change the behavior of the atom (subpattern) next to it. Also, your regex is "broken" because you are putting all subpattern sequences into a character class.

you can use

/^(?!.{11})[a-z]+(?: [a-z]+)?$/

      

See regex demo



If char can be any non-whitespace char, replace [a-z]

with \S

.

Explanation

  • ^

    - beginning of line
  • (?!.{11})

    - do not return a match if 11 characters are found from the beginning of the string (this negative lookahead will work the same as (?=.{1,10}$)

    - from 1 to 10 characters to the end of the string)
  • [a-z]+

    - 1 + lowercase letters (replace with what you really allow)
  • (?: [a-z]+)?

    - 1 or 0 occurrences:


    • - space (can be replaced with \S

      )
    • [a-z]+

      - 1 + lowercase letters (replace with what you really allow)
  • $

    - end of line.
+2


source


I think you don't need to check for the second criterion (10 characters maximum) in the regexp. If anyone has a hammer, they shouldn't use it all over the place. Instead, it simply and straightforwardly checks the exam line length through a property length

.



s = 'asdf asdf'
/^\w+( \w+)?$/.test(s) && s.length <= 10

      

+2


source







All Articles