正则表达式只允许少数特殊字符与 az 或 AZ 一起使用 [英] Regex to allow only few special characters along with az or AZ

查看:35
本文介绍了正则表达式只允许少数特殊字符与 az 或 AZ 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个接受 a-zA-Z 的字段,我正在使用正则表达式,它可以正常工作

There is a field which accepts a-zA-Z for which I am using regEx which works fine as

/^[a-zA-Z\s]+$/

现在字段也应该除了 &,<,> 之外的所有字符我修改了 regEx 以支持此更改,新的 regEx 是

Now field should also except all chars except &,<,> I have modified the regEx to support this change and new regEx is

/^[a-zA-Z\s]+[/!@#$%^&*()]+$/

但看起来它不起作用......有人可以告诉我我做错了什么吗?

but looks like its not working.... Can someone advise what is wrong am I doing ?

另外,我们可以不添加所有允许的特殊字符,而是只添加 RegEX 中不允许的特殊字符吗?

Also, instead of adding all allowed special characters, can we add only special characters which are not allowed in RegEX ?

==================================================================================使用下面的代码验证打字稿中的代码,它应该按照建议工作,但对于所有输入值仍然错误...

================================================================================= Validating the code in typescript using below code, It should work as suggested but still getting false for all input values...

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  private output ;
  private regEx = new RegExp('/^[a-zA-Z\s/!@#$%^&*()]+$/');
  private input = 'A';

  constructor(){
    console.log(this.regEx.test(this.input));
  }
 }

推荐答案

您的模式未按预期工作,因为您在第一个字符集之后添加了另一个字符集,而不是向现有字符集添加其他字符.因此,正则表达式首先会查找一串字母和空格,然后是一串 shift+number 字符.试试这个:

Your pattern isn't working as expected because you added another character set after the first one, instead of adding additional characters to the existing set. So first the regex will look for a string of letters and whitespaces, then a string of shift+number characters. Try this instead:

/^[a-zA-Z\s/!@#$%^&*()]+$/

另外,如果你真的想允许除&、<和>之外的所有字符",需要指出的是还有很多其他字符没有包含在上面的集合中,比如外文字母字符、emojis等.甚至是键盘上的一些,例如 ,.;:;'"[]{}| 和您遗漏的数字.

Also, if you really want to allow "all characters except &, <, and >", it should be pointed out that there are many other characters not contained in the above set, such as foreign alphabet characters, emojis, etc. Even some on the keyboard such as ,.;:;'"[]{}| and numerals that you left out.

如果您真的想匹配&、<和>之外的任何,您应该简单地创建一个带有^<的否定字符类/代码>:

If you truly want to match anything other than &, <, and >, you should simply create a negated character class with ^:

/^[^&<>]+$/

这篇关于正则表达式只允许少数特殊字符与 az 或 AZ 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆