简体   繁体   中英

How to validate that there are no spaces between two characters in a string, using regex

I am trying to validate that there NO spaces between two characters (or in the middle of a name) in a string.

I want a regex that will accept " ab " and reject " ab " .

I tried using "\\\\s*((_[a-zA-z]+)|([a-zA-Z]+[a-zA-Z0-9]*))\\\\s*" and "(\\\\s*\\\\S\\\\s*)" .

ps I don't care about spaces before and after the character\\word.

Thanks in advance!

you can use \\\\s*\\\\S+\\\\s* `

  • \\\\s* match zero or more spaces
  • \\\\S+ match one or more non-space characters
  • \\\\s* match zero or more spaces

     System.out.println(" aa ".matches("\\\\s*\\\\S+\\\\s*")); // true System.out.println(" a bc ".matches("\\\\s*\\\\S+\\\\s*")); // false 

Note : matches implicitly include starting of match ^ and ending of match $ anchors and there is no need of capturing group () unless you are trying to fetch the specified match out of your data.

To match only alphabets use \\\\s*[a-zA-Z]+\\\\s*

Try ^\\s*\\w+\\s*$

This looks for zero or more spaces then any word characters [a-z0-9_] then zero or more spaces again before the end of the string

See demo

You can match exactly N characters with {N}

So, you can just use:

\\S{2}

which matches any two non-whitespace characters; or

\\w{2}

which matches two word characters.

 [a-zA-Z]{2}

two letters, etc.

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