java - 如何在 Java 正则表达式中使用 "and"运算符

标签 java regex string

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/

相关文章:

替换 R 中的字符串 gsub

c# - 正则表达式替换 C# 中的标签

正则表达式匹配没有给定前缀的特定字符串

java - 取一个字符串并将其转换为二维数组 Java

c# - StringBuilder 字符串是不可变的吗?

java - Neo4j Spring ogm 导致关注者-关注者概念的 stackoverflow

java - 无法转换为org.springframework.security.core.userdetails.UserDetails,根本原因是Java spring-boot security错误

java - Java中的数组 "remember"它们的类型如何?

php - 如何将 MySQL 列值从数组转换为字符串

java - "A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property."错误