shw*_*tha 5 java regex special-characters
假设我将一个字符串定义为:
String splChrs = "/-@#$%^&_-+=()" ;
String inputString = getInputString(); //gets a String from end the user
Run Code Online (Sandbox Code Playgroud)
我想检查字符串“ inputString ”是否仅包含字符串“ splChrs ”中包含的特殊字符,即如果inputString仅包含“ splChrs ”中存在的字符,我想将布尔标志设置为true
eg: String inputString = "#######@"; //set boolean flag=true
Run Code Online (Sandbox Code Playgroud)
如果布尔标志包含“ splChrs ”中不包含的任何字母,则布尔标志设置为假
eg: String inputString = "######abc"; //set boolean flag=false
Run Code Online (Sandbox Code Playgroud)
您可以使用:
String splChrs = "-/@#$%^&_+=()" ;
boolean found = inputString.matches("[" + splChrs + "]+");
Run Code Online (Sandbox Code Playgroud)
PS:我已经重新排列了变量中的字符splChrs,以确保连字符开始避免转义。我还从字符串中间删除了一个多余的(且有问题的)连字符,否则会给字符类(表示范围)带来不同的含义。
感谢@AlanMoore 关于字符类中的字符的注释:
^如果它列在第一位;] 如果没有首先列出;[任何地方;如果&紧随其后的是另一个&.
| 归档时间: |
|
| 查看次数: |
17129 次 |
| 最近记录: |