简体   繁体   中英

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

I am looking for the output like 123+12+123=258 but it is also Printing Whitespaces.How to ignore that whitespaces using regex. Any Help would be appreciated. I know we can use "and" operator in regex but don't know how to use being new to regex

You can use Matcher with this regex \\d+ to match only digits instead of split, your code can look like this :

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

If you are using Java9+ you can just use :

String str = "Test123 is12 good123";
int total = Pattern.compile("\\d+").matcher(str)
        .results()
        .mapToInt(m -> Integer.valueOf(m.group())).sum();

If you insist using split you can use this regex [^\\d]+ which will match all non digits, but you still need to check if the array not have empty ones, your code can look like this :

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

A variation on "use split and check for null" is to use streams and 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() );
   }
}

I like YCF's matcher().results() to make a stream, I didn't know a Matcher would do that.

Just to answer the "or" question also, you just use a | and then your pattern gets to be :

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

The + is for 1-n times that.

The problem here is that your first String will be empty as it will split because it finds the pattern, but the left of the pattern is empty.

Doing it the way YCF_L suggested is definitely the way to go through, since you´re looking for the numbers, not for the rest. You should generally always apply the pattern to what you´re looking for, or you end up excluding the universe just to get a set of 10 numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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