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.

Dani AI

Generated

Several workable approaches were mentioned in the replies: suggested regex/Scanner/split, gave a numeric-only replaceAll trick, and used a substring based on a fixed character position. For a clean, robust solution that tolerates minor variations in the prefix (case differences, "No." or "Case#"), prefer a single compiled regex with a capture group. It avoids fragile index math and lets the code validate the result.

import java.util.regex.*;

String text = "Case Number 123-456-789";
Pattern p = Pattern.compile("(?i)\\bcase\\s*(?:number|no\\.?|#)?\\s*(\\S+)$");
Matcher m = p.matcher(text);
String token = m.find() ? m.group(1) : null; // token is null if no match

Pattern notes: (?i) makes matching case-insensitive. (?:number|no\.?|#)? accepts common prefix variants. (\S+)$ captures the final non-whitespace token (the XXX-XXX-XXX). For stricter validation (exact 3-3-3 digits) replace the capture group with (\d{3}-\d{3}-\d{3}). If the case identifier can contain spaces, use (.+)$ and trim the result.

Practical tips: compile the Pattern once (outside loops) for performance, always check for null before using the token, and log or handle strings that fail to match so bad input can be diagnosed. The regex approach balances clarity and resilience; use simpler splitting only when the input format is guaranteed never to vary.

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.