Skip to content
Advertisement

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:

JavaScript

I tried to use it in Java. With string.matches() I don’t have any error. But, with string.replaceFirst, I have this error :

JavaScript

What I tried else ?

  • Remove / at begin and /g at end.
  • Add (pattern) (such as visible in regex here)
  • Multiple others quick way, but I the error is always at the last char of my regex

My full code:

JavaScript

How can I fix it ? How can I solve my regex pattern ?

Advertisement

Answer

You can use

JavaScript

The regex matches

  • n – a newline char (you have a newline in the string, not a backslash and n)
  • [0-9]+ – one or more digits
  • s+ – one or more whitespaces
  • : – a colon
  • s* – zero or more whitespaces

See the Java demo:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement