简体   繁体   English

我可以在 split() 中使用字符串数组来指定分隔符吗?

[英]Can I use an String array within split() to specifier delimiters?

New to java/coding and trying to get to grips with it so thank you in advance for the help!刚接触 java/coding 并试图掌握它,所以提前感谢您的帮助!

I have this string "s" I am splitting using a set of operators as delimiters.我有这个字符串“s”,我使用一组运算符作为分隔符进行拆分。

String[] workableParts = s.split("(?<=[-+*/%^=])|(?=[-+*/%^=])");

I'm storing each split within the workableParts array with the delimiters also stored as part of the array - so for instance an input of 7+7 would be stored as:我将每个拆分存储在 workableParts 数组中,分隔符也存储为数组的一部分 - 例如,输入 7+7 将存储为:

workableParts[0]="7" workableParts[1]="+" workableParts[2]="7"

I also use this operator array elsewhere:我还在其他地方使用这个运算符数组:

private String[] ops = {"-","+","*","/","%","^","="};

Is there a way I can use this to replace the text in the split above but maintain the same effect?有没有办法可以使用它来替换上面拆分中的文本但保持相同的效果? The idea being that if I add operators at a later date I only have to update them in one place.这个想法是,如果我以后添加运算符,我只需在一个地方更新它们。

Many thanks,非常感谢,

Sam山姆

One possible option is to convert your string array to a string using Arrays.toString(ops);一种可能的选择是使用Arrays.toString(ops);将字符串数组转换为字符串。 and use that in the regex expression.并在正则表达式中使用它。 This returns the string of the form [-,+,*,/,...] .这将返回[-,+,*,/,...]形式的字符串。

Now, you can replace the , with an empty string "" and use the substring in your regex.现在,您可以将,替换为空字符串""并在正则表达式中使用 substring。

private String[] ops = {"-","+","*","/","%","^","="};
String joinedOps = Arrays.toString(strArray);
joinedOps = joinedOps.substring(1, str.length()-1).replace(",", "");
String regex = "...."+joinedOps+"...";

You could do something like this.你可以做这样的事情。 Define you own split method and build the regex inside of it.定义您自己的 split 方法并在其中构建正则表达式。 When you change the ops array you will modify the regex.当您更改 ops 数组时,您将修改正则表达式。

Note: You must use caution in the placement of the ops so that they don't construct an unexpected character class.注意:在放置操作时必须小心,以免它们构造出意外的字符 class。 Eg - should be at the front and ^ should never be.例如-应该在前面,而^不应该在前面。

static String[] ops = { "-", "+", "*", "/", "%", "^", "=" };

public static void main(String[] args) {
        String s = "7+7-8^2";

        String[] workableParts = opSplit(s);        
        System.out.println(Arrays.toString(workableParts));     
}

Prints印刷

[7, +, 7, -, 8, ^, 2]

The method方法


public static String[] opSplit(String s) {
    String op = String.join("", ops);
    String regex = "(?<=[" + op + "])|(?=[" + op + "])";
    return s.split(regex);
}

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

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