java 正则匹配非数字
时间: 2023-05-31 10:02:25 浏览: 57
可以使用正则表达式 `\D` 匹配非数字,具体实现可以参考以下示例代码:
```java
String str = "hello123world";
Pattern pattern = Pattern.compile("\\D");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
```
输出结果为:
```
h
e
l
l
o
w
o
r
l
d
```
相关问题
java正则匹配纯数字
根据提供的引用内容,有多种方法可以在Java中使用正则表达式匹配纯数字。引用\[1\]和引用\[2\]中提供了两种不同的正则表达式示例。在引用\[1\]中,使用的正则表达式是"^\[0-9\]+$"或"\[0-9\]+",这两个表达式都可以用于判断一个字符串是否只包含数字。在引用\[2\]中,使用的正则表达式是"^\\d+(\\.\\d+)?$",这个表达式可以用于判断一个字符串是否为数字,包括整数和小数。
以下是一个示例代码,演示如何使用正则表达式在Java中匹配纯数字:
```java
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String\[\] args) {
Main main = new Main();
System.out.println(main.isNumeric("sd21")); // false
System.out.println(main.isNumeric("2113 23")); // false
System.out.println(main.isNumeric("")); // false
System.out.println(main.isNumeric("12#12")); // false
System.out.println(main.isNumeric("-11212")); // true
System.out.println(main.isNumeric("11212")); // true
System.out.println(main.isNumeric("11212SDS")); // false
}
public boolean isNumeric(String str) {
// 使用正则表达式"^\[0-9\]+$"进行匹配
// return Pattern.matches("^\[0-9\]+$", str);
// 使用正则表达式"\[0-9\]+"进行匹配
return Pattern.matches("\[0-9\]+", str);
}
}
```
以上代码中的`isNumeric`方法使用了两种不同的正则表达式进行匹配,你可以根据需要选择其中一种。根据提供的测试数据,该方法将返回相应的布尔值来指示字符串是否为纯数字。
#### 引用[.reference_title]
- *1* *2* *3* [Java中用正则表达式判断字符串是否全是数字](https://blog.csdn.net/u010002184/article/details/99953800)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
java正则表达式匹配非数字字符
可以使用正则表达式中的非数字字符类来匹配非数字字符。在 Java 中,非数字字符类表示为 `\D`。下面是一个示例代码,可以匹配非数字字符:
```
String str = "abc123def456";
Pattern pattern = Pattern.compile("\\D");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
System.out.print(matcher.group());
}
```
输出结果为:`abcdef`,即匹配了字符串中的非数字字符。