문제 발생
String.split()시에 나타났다. "-"일때는 문제 없이 split()이 가능하지만, "^","*","+"인 경우에는 할수 없었다.
public class Main {
public static void main(String[] args) {
String s = "123+456+789";
String[] t = s.split("+"); // Dangling meta character
for(String e : t){
System.out.println(e);
}
}
}
해결 방법
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0 +
I am getting the error when I launch my UI that causes this code to spit the error at me in the title. It works for all of my other operator symbols so I am really not sure what's going on here. I ...
stackoverflow.com
stakOverFlow에 관련된 글을 찾아보면, 해당 문자는 Rex에서 Character로 인식되기 때문에, 문자 앞에 "\\"를 붙여주면 사용할수 있다고 한다.
기존의 String[] t = s.split("+");를 String[] t = s.split("\\+"); 로 변경하면 정상적으로 spli()함수가 진행된다.
public class Main {
public static void main(String[] args) {
String s = "123+456+789";
String[] t = s.split("\\+");
for(String e : t){
System.out.println(e);
}
}
}
<출력 결과>
++
만약 "+"문자 앞뒤로 공백이 있다면, "\\+" 앞뒤로 공백을 넣어주면 된다.
public class Main {
public static void main(String[] args) {
String s = "123 + 456 + 789";
String[] t = s.split(" \\+ ");
for(String e : t){
System.out.println(e);
}
}
}
String[] t = s.split(" + "); 으로 하게되면 split()이 안되고 전체 String이 t에 들어가게 된다.
public class Main {
public static void main(String[] args) {
String s = "123 + 456 + 789";
String[] t = s.split(" + ");
for(String e : t){
System.out.println(e);
}
}
}
<결과>
728x90
'기타' 카테고리의 다른 글
[아이폰] 활성화 등록 서버에 연결할 수 없음, 활성화할 수 없음 (0) | 2021.07.27 |
---|---|
[Error] Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: (0) | 2021.06.30 |