简体   繁体   English

用正则表达式替换字符串时未闭合的字符 class

[英]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" "\n123: 其他" Yes是的 other其他
"123: other" “123:其他” No Error错误
"\n4: smth" "\n4: smth" Yes是的 smth smth
"123: a" “123:一个” 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?我还尝试了什么?

  • Remove / at begin and /g at end.删除开头的/和结尾的/g
  • Add (pattern) (such as visible in regex here )添加(pattern) (例如正则表达式中可见)
  • Multiple others quick way, but I the error is always at the last char of my regex其他多种快速方法,但我的错误总是在我的正则表达式的最后一个字符

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.

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