How to ignore white space with regex?

时光怂恿深爱的人放手 提交于 2021-02-07 21:11:11

问题


Here is my regex:

^(SK{1}[0-9]{8})$

But I want text like this:

SK 283 92758
SK 283 92 7 58

to be taken as this:

SK28392758

It is possible?


回答1:


Use the "optional" quantifier ? for a space between each character:

^S ?K ?(\d ?){7}\d$

This allows an optional space between the characters.
To allow any number of spaces, replace every ? with *.

See live demo.

I also removed unnecessary brackets:

  • {1} is pointless
  • the brackets around the whole thing are unecessary; group 0, which is the whole match, is always available is you absolutely need a capture group



回答2:


You can use the regex ^(SK{1}\s\d{3}\s\d{5})$ and use a String.Replace afterwards to remove the spaces.



来源:https://stackoverflow.com/questions/31309652/how-to-ignore-white-space-with-regex

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