1

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:

/[\\][n](?:[0-9]*)[ ][:]/g

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

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.
  • 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:

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 ?

Elikill58
  • 4,050
  • 24
  • 23
  • 45
  • The `\n` in `"\n"` is a newline, not a backslash and `n`. So, it should be `str = str.replaceFirst("\n[0-9]+\\s+:\\s*", "")`. Do not use `str.matches`. Using `g` (`g`lobal flag to match all occurrences) with `.replaceFirst` is not only invalid, it is not logical. – Wiktor Stribiżew Dec 13 '21 at 20:46
  • Thanks @WiktorStribiżew I don't have error now, but it didn't find something – Elikill58 Dec 13 '21 at 20:48
  • See https://ideone.com/iMAFJS, what did you mean by "it didn't find something"? – Wiktor Stribiżew Dec 13 '21 at 20:50
  • @WiktorStribiżew I didn't change the string. But I found the issue, when I copy paste, I made a typo error. So yes, your regex works fine thanks ! Can you make an answer for this ? :) – Elikill58 Dec 13 '21 at 20:54

1 Answers1

2

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)
  • [0-9]+ - one or more digits
  • \s+ - one or more whitespaces
  • : - a colon
  • \s* - zero or more whitespaces

See the Java demo:

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:

"other"
"123 : other"
"smth"
"123 : a"
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563