Regex to allow only few special characters along with az or AZ

流过昼夜 提交于 2021-02-17 02:30:35

问题


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

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

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 ?

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));
  }
 }

回答1:


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/!@#$%^&*()]+$/

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 ^:

/^[^&<>]+$/




回答2:


Remove the leading and trailing slashes and escape the backslash:

private regEx = new RegExp('^[a-zA-Z\\s/!@#$%^&*()]+$');

You are passing in the regex as a string to the constructor so you need to omit the leading and trailing slashes per the docs.

You are constructing a string so escaping rules matter, you need to escape the backslash so that a literal \s will be provided to the constructor instead of just s.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Description



来源:https://stackoverflow.com/questions/59380759/regex-to-allow-only-few-special-characters-along-with-az-or-az

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!