theConstructor
theConstructor

Reputation: 119

String split after a number and symbol

I have a sample string eg

"ZZZ-1234567890-from ABC-2 DEF"

I need the output to be:

"from ABC-2 DEF"

All the sample strings are in the format

"ZZZ-numbers-Strings"

I need to get the string part after

"ZZZ-numbers-"

I tried using split() but could not solve it. Appreciate the help!

Upvotes: 0

Views: 252

Answers (3)

bodyjares
bodyjares

Reputation: 440

According to your format you probably want to remove the first part "ZZZ-numbers-"

using replaceAll with regex do the trick (inspired by @Shar1er80 answer):

public static void main(String[] args) {
    String data = "ZZZ-1234567890-from ABC-2 DEF";
    System.out.println(data.replaceAll("^.{3}[-][0-9]+[-]","")); 
}

Upvotes: 1

Shar1er80
Shar1er80

Reputation: 9041

UPDATE

After reading your question again, knowing that your Strings are in the format

"ZZZ-numbers-Strings" and you want everything after "ZZZ-numbers-"

Then you can do a split with a regex pattern of "ZZZ-\d+-". This will result in a 2-element array and you want the results at index 1.

public static void main(String[] args) throws Exception {
    String data = "ZZZ-1234567890-from ABC-2 DEF";
    String[] split = data.split("ZZZ-\\d+-");
    System.out.println(split[0]); 
    System.out.println(split[1]); 
}

Results:

(blank line for split[0])
from ABC-2 DEF

OLD ANSWER

This looks more like a job for substring() and indexOf() as long a "from" exists only once in your String and you want to capture everything after "from" including "from".

public static void main(String[] args) throws Exception {
    String data = "ZZZ-1234567890-from ABC-2 DEF";
    System.out.println(data.substring(data.indexOf("from"))); 
}

Results:

from ABC-2 DEF

Upvotes: 1

Codebender
Codebender

Reputation: 14471

Easy, use String.split("ZZZ-\\d+-")[1]

Upvotes: 0

Related Questions