简体   繁体   中英

Check that the input only contains certain characters

I need to check that my input string only contains alphabetic characters, asterisks, spaces, and tabs.

I tried this, but it doesn't work:

firstStr.matches(".*[a-zA-Z].*.*[\\t].*.*[\\s].*") 

Use this regex to check if string contains only alphabets, spaces, asterisks, tabs:

firstStr.matches("[a-zA-Z *\t]+")

You were close, but you needed a single character class.

I believe this should work:

[\\*\\t\\sa-zA-Z]+  //if you want to ensure that there is atleast 1 character in the string

[\\*\\t\\sa-zA-Z]*  //if it is ok to have 0 or more characters in the string

\\* will match an asterisk
\\t will match tab
\\s will match whitespace
a-zA-Z will match alphabetical chars
[...]+ ensures there are atleast one of the expression in the brackets
[...]* means there is 0 or more of the expression in the brackets

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