Regular Expression to Match Non-Whitespace Characters

夙愿已清 提交于 2019-12-02 06:20:51

问题


I need to make a regular expression that matches something like:

JG2144-141/hello

or

!

but not:

laptop bag

or a string consisting of whitespace chars only (' ').

Right now I have [A-Za-z0-9-!/\S], but it isn't working because it still matches with laptop and bag individually. It shouldn't match laptop bag and the empty string at all.


回答1:


The \S in [A-Za-z0-9-!/\S] makes this character class equal to \S, but you want to make sure all chars in the string are non-whitespace chars. That is why you should wrap the pattern with ^ and $ anchors and add a + quantifier after \S to match 1 or more occurrences of this subpattern.

You may use

^\S+$

See the regex demo

Details

  • ^ - start of string
  • \S+ - 1 or more non-whitespace chars
  • $ - end of string.


来源:https://stackoverflow.com/questions/47382087/regular-expression-to-match-non-whitespace-characters

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