Match a string with no white space in between text but may have leading spaces/zeros

StackOverflow https://stackoverflow.com/questions/19977632

  •  30-07-2022
  •  | 
  •  

Frage

Regular expression that matches based on the below

  • It is min 12 or max 13 characters
  • Can have leading spaces/Zeros
  • No blank spaces in the String
  • Not all Zeros/spaces

  • Correct Match: " ABCDEFGHIJ" "ABCDEFGHIJKLM"

  • Wrong Match: "ABCD IJKL"
War es hilfreich?

Lösung

Are you saying the whole string has to be 12 or 13 characters long including the leading whitespace? This will work in most regex flavors:

^(?=.{12,13}$)\s*[A-Za-z0-9]+$

I'm not sure about ABAP though. Many of the search hits I've found suggest that it supports lookaheads, but if you're really using POSIX standard regexes, this won't work. You would probably have to do the length check in a separate test.

UPDATE: To prevent a match of all zeroes, you'll need to add another lookahead:

^(?=.{12,13}$)(?!0+$)\s*[A-Za-z0-9]+$

UPDATE 2: It just occurred to me that you probably don't want strings like " 000000000" -- i.e., all zeroes plus leading spaces. This regex will cover that:

^(?=.{12,13}$)(?!\s*0+$)\s*[A-Za-z0-9]+$

Andere Tipps

You can use this regex:

^ *[A-Za-z0-9]{12,13}$
\s*\b[a-zA-Z0-9]{12,13}\b

This doesn't require the string to be on its own line. If you don't actually care about matching the initial whitespace you can get rid of the \s*

You just want optional leading spaces:

\s*[A-Za-z0-9]{12}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top