简体   繁体   English

如何在Java中拆分具有多个分隔符的String

[英]How to split a String with multiple delimiters in Java

I am trying to have the desired outputs like this: 我想尝试这样的输出:

555
555
5555

by using codes: 使用代码:

public class Split {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String phoneNumber = "(555) 555-5555";

    String[] splitNumberParts = phoneNumber.split(" |-");


    for(String part : splitNumberParts)
        System.out.println(part);

But dont know how to get rid of the "( )" from the first element. 但是不知道如何从第一个元素中删除“()”。

Thanks in advance. 提前致谢。

Regards 问候

StringTokenizer supports multiple delimiters that can be listed in a string as second parameter. StringTokenizer支持多个分隔符,这些分隔符可以作为第二个参数在字符串中列出。

StringTokenizer tok = new StringTokenizer(phoneNumber, "()- ");
String a = tok.nextToken();
String b = tok.nextToken();
String c = tok.nextToken();

In your case, this will give a = 555, b = 555, c = 5555. 在你的情况下,这将给出a = 555,b = 555,c = 5555。

why not do a replace first? 为什么不先替换?

String phoneNumber = "(555) 555-5555";
String cleaned = phoneNumber.replaceAll("[^0-9]",""); // "5555555555"

Then you can use substring to get the parts you want. 然后,您可以使用子字符串来获取所需的部分。

If you just want your digits in sequence, then you can probably make use of Pattern and Matcher class, to find all the substrings matching a particular pattern, in your case, \\d+ . 如果您只想按顺序排列数字,那么您可以使用PatternMatcher类来查找匹配特定模式的所有子字符串,在您的情况下, \\d+

You would need to use Matcher#find() method to get all the substrings matching your pattern. 您需要使用Matcher#find()方法来获取与您的模式匹配的所有子字符串。 And use Matcher#group() to print the substring matched. 并使用Matcher#group()打印匹配的子字符串。

Here's how you do it: - 这是你如何做到的: -

String phoneNumber = "(555) 555-5555";

// Create a Pattern object for your required Regex pattern
Pattern pattern = Pattern.compile("\\d+");

// Create a Matcher object for matching the above pattern in your string
Matcher matcher = pattern.matcher(phoneNumber);

// Use Matcher#find method to fetch all matching pattern.
while (matcher.find()) {
    System.out.println(matcher.group());
}

When you're using split java will return an array of string which is separated from where there was an occurence of the items which you provided, thus if you where to do a split like you are doing now, you could add something like this: 当你使用split时,java将返回一个字符串数组,该字符串与你提供的项目的出现位置分开,因此,如果你像现在这样进行拆分,你可以添加如下内容:

phoneNumber.split(" |-|\\(|\\) ");

But thats not very nice looking, now is it? 但那不是很好看,现在是吗? So instead we can do something like this, which basically tells java to remove anything that isn't a number: 所以我们可以这样做,基本上告诉java删除任何不是数字的东西:

String[] splitNumberParts = phoneNumber.split("\\D+");

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

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