简体   繁体   中英

How to isolate specific words from a string in Java?

I've looked into other similar posts, and all the ones I've seen are strings with spaces. How about splitting strings that do not contain any spaces? I know how to separate the numbers, but I'm not sure about splitting specific words like Delta, Sigma, Gamma, and Alpha.

// the one below is the string to be separated
//11020#Delta-99998#Sigma-45201#Gamma-69420#Gamma-90967#Alpha-

int[] numbers = new int[numberOnly.length()];
for(int i =0; i<numberOnly.length();i++) {
    numbers[i] = numberOnly.charAt(i)-'0';
            }
            

Use Or Operator

class Regx{
    public static void main(String ...$){
        String s = "11020#Delta-99998#Sigma-45201#Gamma-69420#Gamma-90967#Alpha-";
        var out = System.out;
        String arr[] = s.split("Delta|Sigma|Gamma|Alpha");
        for(var a : arr)
            out.println(a);
    }
}

Output:

$ java Regx 
11020#
-99998#
-45201#
-69420#
-90967#
-

If you want to separate # and - as well:

import java.util.stream.Stream;
import java.util.stream.Collectors;
class Regx{
    public static void main(String ...$){
        String s = "11020#Delta-99998#Sigma-45201#Gamma-69420#Gamma-90967#Alpha-";
        var out = System.out;
        var arr = Stream.of(s.split("Delta|Sigma|Gamma|Alpha|#|-")).filter(str->str.length() !=0).collect(Collectors.toList());
        for(var a : arr)
            out.println(a);
    }
}

Output:

$ javac Regx.java && java Regx
11020
99998
45201
69420
90967

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