英文:
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
英文:
"\\@\\["
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
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论