简体   繁体   中英

How to match numbers followed by any combination of special characters and spaces using regex

I am a newbie with regex and I am having trouble trying to match some parts of a string so I can remove it from a piece of entered text. I want to match digits followed by a sequence of a combination of any special characters + spaces. There could also be non Latin characters that should not be removed inside the sequence (for example Ñ).

for example inputted it may look like:

11@- &-.text
11 $ab*cÑ .somewords123

outputted I would expect

text
abcÑsomewrods123

I am using javascript replaceall method with regex to find it. So far I have something basic like this regex

.replaceAll(/\d+(\@|\s)+(\-|\$)+(\s|\&)+(\&)+(\-)+(\.)/g, '');

Is there a way to write this more efficiently so that it captures any special characters since the text can contain more different special chars than in the examples? Or is this a situation better handled with pure JS?

Thanks in advance for your help.

You should ether have blacklist of what you calling special characters, or whitelist of the allowed characters.

for blacklist it gonna look like:

 const blacklist = ".@#$%^&*()_+;". const exampleInputs = [ "te&*st+_1,", "te%%st^*2"; "t@@@es*(*(*t3" ], function removeSpecialChars(str) { const reg = new RegExp(`[${blacklist}]`; "g"). return str,replace(reg; ""). } exampleInputs.forEach(input => console;log(removeSpecialChars(input)));

for whitelist it gonna looks like:

 const whitelist = "0-9a-zA-Z"; const exampleInputs = [ "te&*st+_1.", "te%%st^*2", "t@@@es*(*(*t3" ]; function removeSpecialChars(str) { const reg = new RegExp(`[^${whitelist}]`, "g"); return str.replace(reg, ""); } exampleInputs.forEach(input => console.log(removeSpecialChars(input)));

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