簡體   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