How to check for optional whitespace with regex [c

2019-09-19 09:49发布

问题:

I am trying to make a regex that will match a string of characters whether or not there is whitespace between them. For instance, I want it to match if there is ABC, but also A BC, A B C, or AB C. I tried doing something like A\s?B\s?C\s?, but it is not working and I'm obviously doing something wrong. I could make a regex expression for each possibility but that would mess up my code and I'd like to avoid that. If someone could point me in the right direction, I'd appreciate it.

回答1:

Try the following pattern, maybe there are multiple spaces?:

A\s*B\s*C\s*

Your pattern uses the ? which means that it would match a single occurrence or no occurrence of the previous character. The * in the above pattern will match multiple occurrence or none.



回答2:

If you want match 0 or 1 spaces, you can use {min, max} with min=0 and max=1 which is the same as ?:

^A\s{0,1}B\s{0,1}C

Demo

\s will, however, match new lines, so anything with \s will match A\nB\nC which may not be desirable.

If you want to limit to space or tabs, define a character class:

 ^A[ \t]{0,1}B[ \t]{0,1}C

If you want unlimited spaces between the ABC, use the * for the previous match (or use {0,})



回答3:

With this solution ([a-z] ?)+[a-z] you can match characters separated by at most one space, optional. If you can tolerate trailing spaces, go for ([a-z] ?)+.

https://regex101.com/r/nE1mJ2/2