简体   繁体   中英

Make regex allow letters, numbers and special characters

I have search for a regex to not allow more that one space between words, and I get this:

'^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$'

It's working, but I realize that is not accepting special characters, so I implemented:

'^[a-zA-Z0-9!@#$&?!*%()\\-`.+,/\"]+(?: [a-zA-Z0-9!@#$&?!*%()\\-`.+,/\"]+)*$'

But it make me wonder if it has other formula so can i accepted all letters, numbers and all special characters, without having to write all the special characters.

Example: 'Test Test' If it has more than one spacing between words like this, the regex need to catch that.

If my regex is right, you should be able to use
\\S+ \\S+
'\\S' is any char that isn't whitespace. All symbols and letters are included in '\\S', and we have '+' for any 1 or more of those. Then with a single space in-between, it will only match words that have one space between them. However, make sure your careful if you are applying this to a big file. This will not check every word pair. If two words match with only one space, then they will be pulled, and the second word would not be tested against the second;

one two three

In this case, only one two would be grabbed, and three would never be checked with two because we found a match. An easier approach for making sure there arent doubble spaces could be to specifcially find all the doubble spaces in your text and deal with them how you must.

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