package com.javaprograms;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Remove_Elements_From_String {
public static void main(String[] args) {
String str = "Test123 is12 good123";
int total = 0;
Pattern p = Pattern.compile("[a-zA-Z]");
String[] m = p.split(str);
for (String s : m) {
System.out.println(s.toString());
int num = Integer.parseInt(s);
total = total + num;
}
System.out.println("Total of above string is:" + total);
}
}
我正在寻找类似 123+12+123=258
的输出,但它也在打印空格。如何使用正则表达式忽略该空格。任何帮助,将不胜感激。我知道我们可以在正则表达式中使用“和”运算符,但不知道如何使用正则表达式新手
最佳答案
您可以将 Matcher 与此正则表达式一起使用 \d+
要仅匹配数字而不是拆分,您的代码可以如下所示:
String str = "Test123 is12 good123";
int total = 0;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
while (m.find()) {
total += Integer.parseInt(m.group());
}
System.out.println("Total of above string is: " + total);//Total of above string is: 258
如果你使用的是 Java9+,你可以使用:
String str = "Test123 is12 good123";
int total = Pattern.compile("\\d+").matcher(str)
.results()
.mapToInt(m -> Integer.valueOf(m.group())).sum();
如果你坚持使用 split 你可以使用这个正则表达式 [^\d]+
它将匹配所有非数字,但是你仍然需要检查数组是否没有空的,你的代码可以看起来像这样:
String str = "Test123 is12 good123";
int total = 0;
String[] m = str.split("[^\\d]+");
for (String s : m) {
if (!s.equals("")) {
total += Integer.parseInt(s);
}
}
System.out.println("Total of above string is:" + total);
关于java - 如何在 Java 正则表达式中使用 "and"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004129/