ex0b1t
ex0b1t

Reputation: 1342

Java Regex Substring

Hi i have a string and would like to extract a sub-string that matches a regex the code i currently have removes the sub-string i want it to be the only part that should be kept.

What i have, this removes it, i want to keep it:

String ticketReference = "You have been assigned to the following Support Ticket: ST-00003 bla bla bla";

ticketReference =  ticketReference.replaceAll("'((ST-)[0-9]{5})", " ");

Desired Output : "ST-00003"

Thanx in Advance

Upvotes: 1

Views: 450

Answers (2)

dacwe
dacwe

Reputation: 43504

The replaceAll solution has no error handling so if the match isn't found the string is left unchanged.


Here is a proper way to do it using Pattern and Matcher (and in my mind much easier):

String stringToDecode = 
     "You have been assigned to the following Support Ticket: ST-00003 bla bla";

Matcher m = Pattern.compile("ST-[0-9]{5}").matcher(stringToDecode);

if (!m.find())
    throw new CouldNotFindTicketException(stringToDecode);

String ticketReference = m.group();
//...

Upvotes: 0

Keppil
Keppil

Reputation: 46239

You can use capture groups to do this, they are denoted $n in Java:

String ticketReference = "You have been assigned to the following Support Ticket: ST-00003 bla bla bla";
ticketReference =  ticketReference.replaceAll("^.*(ST-[0-9]{5}).*$", "$1");

Upvotes: 3

Related Questions