java 校验特殊字符正则表达式
时间: 2023-08-31 17:09:06 浏览: 127
正则表达式,数字校验,字符校验,特殊需求表达
在Java中,可以使用正则表达式来校验特殊字符。以下是几个使用正则表达式校验特殊字符的例子:
例子一:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternUtil {
public static void main(String[] args) {
String name = "中山\\浩二/";
Pattern userNameRegex = Pattern.compile("[^a-zA-Z0-9-_~!@]");
Matcher m = userNameRegex.matcher(name);
if (m.find()) {
System.out.println(name + "中含有特殊字符!");
} else {
System.out.println(name + "中不含有特殊字符!");
}
}
}
```
例子二:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternUtil {
public static void main(String[] args) {
String input = "!!!!!!!!@@@";
String pattern = "^[!@]+$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
if (m.matches()) {
System.out.println("input只由!和@组成");
} else {
System.out.println("input包含!和@以外的字符");
}
}
}
```
例子三:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternUtil {
public static void main(String[] args) {
String input = "hello world";
String pattern = "^[a-zA-Z0-9~!@#$%&*()-_]+$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
if (m.matches()) {
System.out.println("input验证成功");
} else {
System.out.println("input验证失败");
}
}
}
```
以上是几个可以校验特殊字符的Java正则表达式的例子。你可以根据自己的需求选择适合的正则表达式进行校验。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Java校验入参之正则表达式校验特殊字符](https://blog.csdn.net/weixin_42586723/article/details/115371602)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Java正则表达式验证字符串格式](https://blog.csdn.net/weixin_41408714/article/details/128666500)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文