繁体   English   中英

如何在Java正则表达式中使用“和”运算符

[英]How to use “and” operator in Regex in Java

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);

“使用拆分并检查是否为空”的一种变体是使用流和filter

public class RegexNumOnly {
   public static void main( String[] args ) {
      String test = "Test123 is12 good443";
      String[] tokens = test.split( "[a-zA-Z\\s]+" );
      System.out.println( Arrays.toString( tokens ) );
      System.out.println( Arrays.stream( tokens ).filter( s -> !s.isEmpty() )
              .mapToInt( Integer::parseInt ).sum() );
   }
}

我喜欢YCF的matcher().results()创建流,但我不知道Matcher会这样做。

只需回答“或”问题,您只需使用| 然后您的模式变为:

Pattern.compile("([a-z]|[A-Z])+")

+是该值的1-n倍。

这里的问题是您的第一个String将为空,因为它将找到模式,它将拆分,但是模式的左侧为空。

按照YCF_L建议的方式进行操作绝对是必经之路,因为您要查找的是数字,而不是其余的数字。 通常,您应该始终将模式应用于所需的内容,否则最终将Universe排除在外而只是获得一组10个数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM