Skip to content
Advertisement

Regex match all text after dash

I try to get all text after hyphen (dash). For example, if I have a text like this:

123-text

I need to get text.

I tried this:

^.*(?=(-))

But it matches all text after dash with that dash and I need to get just text.

Advertisement

Answer

You can remove all text before the first occurrence of a hyphen and the hyphen(s) right after with

String result = text.replaceFirst("^[^-]*-+", "");

See the regex demo. The replaceFirst will find and remove the first occurrence of

  • ^ – start of string
  • [^-]* – zero or more chars other than -
  • -+ – one or more - chars.

An approach with String#split is also viable:

String text = "123-text";
String[] chunks = text.split("-", 2);        // limit splitting into 2 chunks
System.out.println(chunks[chunks.length-1]); // Get the last item
// => text

See the Java demo online.

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