正则表达式验证器字母数字允许空字段,但不允许只有空格

时间:2021-03-05 18:19:58

标签: java regex

我正在尝试编写一个正则表达式验证器,允许

只有字母数字

  • a-z、A-Z、连字符、下划线、空格和空字段(无符号 !@#$% 等)
  • 然而,限制只有空格的字段,(如果存在字符,则允许在开头、中间和结尾使用空格)

这似乎有效,只是想知道我们是否可以让它更干净。

/^$|(?!\s+$)[a-zA-Z0-9-_ ]+$/

尝试通过这些单元测试:

  it('validator should allow alphanumeric characters', () => {
    formGroup.get(productName).patchValue('ABCabc1234');
    formGroup.updateValueAndValidity();
    expect(formGroup.valid).toBeTrue();
  });

  it('validator should not allow symbols', () => {
    formGroup.get(productName).patchValue('ABCabc@#$%1234');
    formGroup.updateValueAndValidity();
    expect(formGroup.invalid).toBeTrue();
  });

  it('validator should allow empty field', () => {
    formGroup.get(productName).patchValue('');
    formGroup.updateValueAndValidity();
    expect(formGroup.valid).toBeTrue();
  });

  it('validator should allow space among words', () => {
    formGroup.get(productName).patchValue('  ABC abc1234 xyz   ');
    formGroup.updateValueAndValidity();
    expect(formGroup.valid).toBeTrue();
  });

  it('validator should not allow all whitespaces', () => {
    formGroup.get(productName).patchValue('   ');
    formGroup.updateValueAndValidity();
    expect(formGroup.invalid).toBeTrue();
  });

2 个答案:

答案 0 :(得分:2)

您可以使用量词 *,表示 zero or more occurrences

另外,you can use \w 代替 [A-Za-z0-9_]

最后的正则表达式可以是 (?!\s+$)[\s\w-]*,其中 (?!\s+$) 为一行末尾的一个或多个空白字符指定 Negative Lookahead

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] arr = { "ABCabc1234", "ABCabc@#$%1234", "", "  ABC abc1234 xyz   ", "    " };

        for (String s : arr) {
            System.out.println(s + " => " + s.matches("(?!\\s+$)[\\s\\w-]*"));
        }
    }
}

输出:

ABCabc1234 => true
ABCabc@#$%1234 => false
 => true
  ABC abc1234 xyz    => true
     => false

答案 1 :(得分:1)

您可以省略交替,并编写可选重复字符类的模式:

^(?!\h+$)[a-zA-Z0-9-_\h]*$

模式匹配:

  • ^ 字符串开头
  • (?!\h+$) 否定前瞻,不仅断言水平空白字符
  • [a-zA-Z0-9-_\h]* 可以选择匹配任何列出的也允许空字符串
  • $ 字符串结束

Regex demo

请注意,\s 也可以匹配换行符。

在 Java 中

String regex = "^(?!\\h+$)[a-zA-Z0-9-_\\h]*$";
相关问题