我尝试在split()方法中使用多个符号来分割我的字符串,但它不起作用。

huangapple go评论65阅读模式
英文:

I'm trying to split my string with multiple symbols in split() method but it's not working

问题

我尝试拆分我的正则表达式,但出现了一些问题。这是我的代码:

String str = "sdef@srdfsrd[es[edf@edfv";
String[] arrOfStr = str.split("\\@\\["); 
for (String a : arrOfStr) 
{
  System.out.println(a);
}

输出:

sdef@srdfsrd[es[edf@edfv

期望的输出:

sdef
srdfsrd
es
edf
edfv

对于相同的问题:

String[] arrOfStr = str.split(",:");  //根本不拆分单词

(没有期望的输出)

英文:

I'm trying to split my regex but it's not splitting for some reason. Here's my code

String str = "sdef@srdfsrd[es[edf@edfv";
String[] arrOfStr = str.split("\\@\\["); 
for (String a : arrOfStr) 
{
  System.out.println(a);
}

output:

sdef@srdfsrd[es[edf@edfv

expected output:

sdef
srdfsrd
es
edf
edfv

The same problem for:

String[] arrOfStr = str.split(",:");  //not splitting the word at all

答案1

得分: 4

"\\@\\[" 匹配 @[,这在你的字符串中 不存在。将你的正则表达式改为 "[@\\[]",这是一个字符类 - 这意味着它将在@[上分割。

在这里查看演示:https://regex101.com/r/A8W2RB/1 我尝试在split()方法中使用多个符号来分割我的字符串,但它不起作用。

英文:

"\\@\\[" matches @[, which is not in your string. Change your RegEx to "[@\\[]", which is a character class - that means it will split on either @ or [.

See a demo here 我尝试在split()方法中使用多个符号来分割我的字符串,但它不起作用。

答案2

得分: 1

使用 "@|\\[ 替代 \\@\\[

请注意,在正则表达式模式中,| 被用作逻辑“或”操作,即通过使用 "@|\\[,您正在指示代码在给定字符串上进行分割,要么在 @ 处分割,要么在 [ 处分割。

或者,您可以使用 [@\\[],其中 [] 指定了字符类

示例:

public class Main {
    public static void main(String[] args) {
        String str = "sdef@srdfsrd[es[edf@edfv";
        String[] arrOfStr = str.split("@|\\[");
        for (String a : arrOfStr) {
            System.out.println(a);
        }
    }
}

输出:

sdef
srdfsrd
es
edf
edfv
英文:

Use "@|\\[ instead of \\@\\[

Note that in regex pattern, | works as OR i.e. by using "@|\\[ you are instructing the code to split the given string either on @ OR on [

Alternatively, you can use [@\\[] where [] specifies the character classes.

Demo:

public class Main {
    public static void main(String[] args) {
        String str = "sdef@srdfsrd[es[edf@edfv";
        String[] arrOfStr = str.split("@|\\[");
        for (String a : arrOfStr) {
            System.out.println(a);
        }
    }
}

Output:

sdef
srdfsrd
es
edf
edfv

huangapple
  • 本文由 发表于 2020年8月5日 03:13:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63253643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定