Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Regex: Allow all characters except four, restriction including underscore

I am not very familiar with regex.

I am trying to implement some restrictions on input. I want to allow all numbers and characters, with special characters like ~"$#*@ etc. except these 4: & ' % _.

I tried like:

/[a-zA-Z0-9-!@#$^*)(+=.-~"]/

But it is not restricting the _ underscore. How can I restrict underscore, and is there any best way to allow all except 4 without writing all symbols in regex?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is that your range .-~ (index 46-126) includes underscore (index 95). So you can either figure out what chars are 46-94 and 96-126 or use a lookahead to omit the undesired chars:

(?=[^&'%_])[a-zA-Z0-9-!@#$^*)(+=.-~"]

https://regex101.com/r/rV0gxb/1


You can also negate like this is it's easier to read:

(?![&'%_])[a-zA-Z0-9-!@#$^*)(+=.-~"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...