我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:

part1 = "004";
part2 = "034556";

这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。

我还想检查字符串中是否有“-”。


当前回答

你真正需要考虑的方法只有两种。

使用String.split作为一个字符分隔符,否则您不关心性能

如果性能不是问题,或者分隔符是不是正则表达式特殊字符的单个字符(即,不是.$|()[{^?*+\之一),则可以使用String.split。

String[] results = input.split(",");

如果delimeter是单个字符而不在上面的列表中,则split方法有一个优化,以避免使用正则表达式。否则,它必须编译正则表达式,这是不理想的。

如果使用复杂的分隔符并且您关心性能,请使用Pattern.split并预编译模式。

如果性能是一个问题,并且分隔符不是上述问题之一,那么应该预先编译一个正则表达式模式,然后可以重用它。

// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");

/// ... later
String[] results = pattern.split(input);

最后一个选项仍然会创建一个新的Matcher对象。您还可以缓存此对象并为每个输入重置它以获得最大性能,但这有点复杂,而且不线程安全。

其他回答

要拆分字符串,请使用string.split(正则表达式):

String phone = "004-034556";
String[] output = phone.split("-");
System.out.println(output[0]);
System.out.println(output[1]);

输出:

004
034556

你真正需要考虑的方法只有两种。

使用String.split作为一个字符分隔符,否则您不关心性能

如果性能不是问题,或者分隔符是不是正则表达式特殊字符的单个字符(即,不是.$|()[{^?*+\之一),则可以使用String.split。

String[] results = input.split(",");

如果delimeter是单个字符而不在上面的列表中,则split方法有一个优化,以避免使用正则表达式。否则,它必须编译正则表达式,这是不理想的。

如果使用复杂的分隔符并且您关心性能,请使用Pattern.split并预编译模式。

如果性能是一个问题,并且分隔符不是上述问题之一,那么应该预先编译一个正则表达式模式,然后可以重用它。

// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");

/// ... later
String[] results = pattern.split(input);

最后一个选项仍然会创建一个新的Matcher对象。您还可以缓存此对象并为每个输入重置它以获得最大性能,但这有点复杂,而且不线程安全。

根据文档:

public String[]split(Stringregex,int limit)围绕给定正则表达式的匹配项拆分此字符串。此方法返回的数组包含此字符串的子字符串,该子字符串由另一个与给定表达式匹配或以一串数组中的子字符串的顺序如下出现在此字符串中。如果表达式与输入,则结果数组只有一个元素,即一串

基本上你可以这样做:

String s = "123-456-789-123"; // The String to be split
String[] array = s.split("-"); // Split according to the hyphen and put them in an array
for(String subString : array){ // Cycle through the array
   System.out.println(subString);
}

输出:

123
456
789
123

如果要验证字母数字,请将正则表达式更改为[A-Za-z0-9]+-[A-Za-z 0-9]+

    public static final Pattern VALIDATE_PATTERN = Pattern.compile("[0-9]+-[0-9]+");

public static String[] validateString(String str) {
    if(VALIDATE_PATTERN.matcher(str).find()) {
        String[] output = str.split("-");
        if(output.length != 2) {
            throw new RuntimeException("Invalid string format");
        }
        return output;
    } else {
        throw new RuntimeException("Invalid string format");
    }
}

使用模式是Java 8。下面是路!!

package com.company;

import java.util.regex.Pattern;

public class umeshtest {

    public static void main(String a[]) {
        String ss = "I'm Testing and testing the new feature";
        Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
    }
}