简体   繁体   English

仅对空白空间进行RegEx验证; 应该接受单词/字符之间的空格

[英]RegEx validation for only empty space; should accept space between words/characters

I'm writing reg ex for UI validation for following requirements: 我正在为以下要求编写reg ex进行UI验证:

  1. It should contain alphabets and/or numbers. 它应包含字母和/或数字。
  2. It can contain "_"(the only acceptable Special character). 它可以包含“ _”(唯一可接受的特殊字符)。
  3. "white space" in between the characters can be acceptable. 字符之间的“空白”是可以接受的。
  4. No empty space (only white spaces are not allowed). 不得有空白空间(不允许使用空格)。

Here's my reg ex: 这是我的前任:

Validators.pattern('^[A-Za-z0-9? ,_-]+$')

Now except '#4', everything else is working fine. 现在,除了“#4”之外,其他所有东西都工作正常。 It's just accepting only white space; 它只接受空白; whereas as per requirement white space can be allowed only in between characters. 而根据要求,只能在字符之间使用空格。

The regex becomes heavier, but you can do this: 正则表达式变得更重,但是您可以这样做:

Validators.pattern('^[A-Za-z0-9?,_-](\s?[A-Za-z0-9?,_-]+)*$')

This ensures that: 这样可以确保:

  • The first character is a valid character, and not a space 第一个字符是有效字符,而不是空格
  • The string either ends here, or 字符串要么在此处结束,要么
    • Contains any sequence of [optional whitespace][at least one valid non-whitespace character] 包含任何序列的[optional whitespace][at least one valid non-whitespace character]

So that these match: 使这些匹配:

  • "aa" “AA”
  • "a" “一种”
  • "aa" “AA”

And these don't: 而且这些没有:

  • "" (not sure if you want this one to match) “”(不确定是否要与此匹配)
  • "a " “一种 ”
  • " a" “ 一种”
  • "aaa " “啊!”

Note: I used your pattern, which allows ? 注意:我使用了您的模式,这允许? , , and - which are not included in your second requirement. ,-其中不包括在你的第二个要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM