简体   繁体   中英

Regexp to match pattern only if non-empty

Hope someone can help me translate this to regex, or point me to the right places. Most questions are about how to check a blank or how to match a pattern, but not the following:

  1. Strip all empty spaces that're followed by nothing (to capture the idea that someone has entered multiple spaces..this to us is a blank)
  2. If blank after stripping, then do nothing
  3. If non-blank, then match pattern XYZ

We know our pattern. The XYZ stuff works. What doesn't work is that this has become a required pattern match. We want this pattern to be validated only if the value is non-blank. How do we capture that in the same regex?

Just to clarify: the language is Javascript.

Regexp is not always the magic stuff which can achieve everything. For the 2 first points, just use standard javascript :

str = str.trim();
if (str && /xyz/.test(str)) {
    // Do fabulous stuff here
}

Anyway, if you want a regexp for that, you can try this :

/^[\t\n\r ]*XYZ[\t\n\r ]*$/

This regexp won't be valid for an empty string. Except if XYZ is something like .* of course.

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