4

我正在尝试拆分一个字符串,如下面的字符串

3x2y3+5x2w3–8x2w3z4+3-2x2w3+9y–4xw–x2x3+8x2w3z4–4

到没有任何数字或符号的字符串表。

这意味着

a[0]=x
a[1]=y
a[2]=x
a[3]=w

我试过这个

split("(\\+|\\-|\\d)+\\d*")

但似乎它不起作用。

4

6 回答 6

5

以下应该有效:

String[] letters = input.split("[-+\\d]+");
于 2012-12-19T20:17:44.160 回答
3

编辑: -

如果你想xw在你的结果数组中在一起,那么你需要拆分你的字符串:-

String[] arr = str.split("[-+\\d]+");

输出: -

[, x, y, x, w, x, w, z, x, w, y, xw, x, x, x, w, z]

您可以用空字符串替换所有不需要的字符,并在空字符串上拆分。

String str = "3x2y3+5x2w3-8x2w3z4+3-2x2w3+9y-4xw-x2x3+8x2w3z4-4";
str = str.replaceAll("[-+\\d]", "");        
String[] arr = str.split("");       
System.out.println(Arrays.toString(arr));

请注意,这将添加一个空字符串作为您可以处理的数组的第一个元素。

输出: -

[, x, y, x, w, x, w, z, x, w, y, x, w, x, x, x, w, z]

请注意,-您的问题登录是不同的。您应该将其替换为键盘上的那个。目前它不是匹配的-标志。

于 2012-12-19T20:17:25.160 回答
1

这一条线可以做到这一切:

String[] letters = input.replaceAll("(^[^a-z]*)|([^a-z]*$)", "").split("[^a-z]+");

这也处理前导/尾随字符,因此您不会在数组的开头得到空白元素(就像其他一些答案一样)

用你的字符串进行测试:

public static void main(String[] args) {
    String input = "3x2y3+5x2w3–8x2w3z4+3-2x2w3+9y–4xw–x2x3+8x2w3z4–4";
    String[] letters = input.replaceAll("(^[^a-z]*)|([^a-z]*$)", "").split("[^a-z]+");
    System.out.println(Arrays.toString(letters));
}

输出:

[x, y, x, w, x, w, z, x, w, y, xw, x, x, x, w, z]

请注意,数组中没有前导“空白”元素

于 2012-12-19T20:14:49.917 回答
0

备注 - 和 - 不是相同的代码,一个只是 ascii 减去另一个是 long (编码 UTF8 e28093 )

public class Test {
    public static void main(String pArgs[])
    {
        String s="3x2y3+5x2w3–8x2w3z4+3-2x2w3+9y–4xw–x2x3+8x2w3z4–4";
        String splitreg="(\\+|\\-|\\d|–)+\\d*";     if ( pArgs.length > 0 )
            {
                splitreg=pArgs[0];
        }
        System.out.println("splitting '" + s + "' with '"  + splitreg + "'"); 
        String[] splitted=s.split(splitreg);
        for (int i=0; i < splitted.length; i++ )
            {
                System.out.println("["+ i + "]" + "=" + splitted[i]);
            }
    }
}

/usr/lib/jvm/java-1.7.0-openjdk-amd64/bin/java 测试

splitting '3x2y3+5x2w3–8x2w3z4+3-2x2w3+9y–4xw–x2x3+8x2w3z4–4' with '(\+|\-|\d|–)+\d*'
[0]=
[1]=x
[2]=y
[3]=x
[4]=w
[5]=x
[6]=w
[7]=z
[8]=x
[9]=w
[10]=y
[11]=xw
[12]=x
[13]=x
[14]=x
[15]=w
[16]=z
于 2012-12-19T20:23:33.157 回答
0
String[] letters = input.split("[\\d\\+\\-]+");
于 2012-12-19T20:25:42.370 回答
0

这是你想要达到的目标吗?

 String data="3x2y3+5x2w3–8x2w3z4+3-2x2w3+9y–4xw–x2x3+8x2w3z4–4";

 //lets replace all unnecessary elements with spaces
 data=data.replaceAll("[-+–\\d]", " ");
 // now string looks like:
 // " x y   x w   x w z     x w   y  xw x x   x w z   "

 // lets remove spaces from start and end
 data=data.trim();
 // data looks like:
 // "x y   x w   x w z     x w   y  xw x x   x w z"

 // and split in places where is at least one space
 String[] arr=data.split("\\s+");

 System.out.println(Arrays.toString(arr));

输出:

[x, y, x, w, x, w, z, x, w, y, xw, x, x, x, w, z]
于 2012-12-19T20:52:02.783 回答