[英]Unclosed character class while replacing string with regex
I want to remove a string at the beginning of another.我想删除另一个开头的字符串。
Example:例子:
Begin![]() |
Removed![]() |
Final![]() |
---|---|---|
"\n123: other" ![]() |
Yes![]() |
other![]() |
"123: other" ![]() |
No![]() |
Error![]() |
"\n4: smth" ![]() |
Yes![]() |
smth ![]() |
"123: a" ![]() |
No![]() |
Error![]() |
Thanks to Regexr , I made this regex:感谢Regexr ,我制作了这个正则表达式:
/[\\][n](?:[0-9]*)[ ][:]/g
I tried to use it in Java.我尝试在 Java 中使用它。 With
string.matches()
I don't have any error.使用
string.matches()
我没有任何错误。 But, with string.replaceFirst
, I have this error:但是,使用
string.replaceFirst
,我有这个错误:
java.util.regex.PatternSyntaxException: Unclosed character class near index 24
/[\][n](?:[0-9]*)[ ][:]/g
^
What I tried else?我还尝试了什么?
/
at begin and /g
at end./
和结尾的/g
。(pattern)
(such as visible in regex here )(pattern)
(例如在正则表达式中可见)My full code:我的完整代码:
String str = "\n512 : something"; // I init my string
if(str.matches("/[\\][n](?:[0-9]*)[ ][:]/g"))
str = str.replaceFirst("/[\\][n](?:[0-9]*)[ ][:]/g", "");
How can I fix it?我该如何解决? How can I solve my regex pattern?
如何解决我的正则表达式模式?
You can use您可以使用
.replaceFirst("\n[0-9]+\\s+:\\s*", "")
The regex matches正则表达式匹配
\n
- a newline char (you have a newline in the string, not a backslash and n
) \n
- 换行符(字符串中有换行符,而不是反斜杠和n
)[0-9]+
- one or more digits [0-9]+
- 一位或多位数字\s+
- one or more whitespaces \s+
- 一个或多个空格:
- a colon :
- 一个冒号\s*
- zero or more whitespaces \s*
- 零个或多个空格See the Java demo :请参阅Java 演示:
List<String> strs = Arrays.asList("\n123 : other", "123 : other", "\n4 : smth", "123 : a");
for (String str : strs)
System.out.println("\"" + str.replaceFirst("\n[0-9]+\\s+:\\s*", "") + "\"");
Output: Output:
"other"
"123 : other"
"smth"
"123 : a"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.