I have strings in Java where each one is as follows: "Case Number XXX-XXX-XXX"
The "XXX-XXX-XXX" part is different for each string. I want to just extract the "XXX-XXX-XXX" portion of each string. I am assuming this is the third token in the string. What would be the best way of doing this? thanks.

Recommended Answers

All 3 Replies

Regular expressions, Scanner, or String.split() will all work for that.

I have strings in Java where each one is as follows: "Case Number XXX-XXX-XXX"
The "XXX-XXX-XXX" part is different for each string. I want to just extract the "XXX-XXX-XXX" portion of each string.

If the XXXs you represented here are numbers as with "Case Number 123-456-789", then the answer lies in a simple RegEx manipulation as follows:

// The token String variable holds the 'XXX-XXX-XXX' part of the text String
String text = "Case Number 123-456-789";
String token = text.replaceAll("[\\D[\\s]]", " ").trim().replaceAll(" ", "-");

But the above would only work if the XXXs are all numbers and not alphabets or any other symbol.

try StringBuffer() easier, faster and easier to read than a Regex solution

String one = "Case number 123-456-789";
String two = one.substring(one.indexOf("r") + 2, one.length());
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.