-4

I need regex to extract the record number from the string below,

String extract = "Purchase Order HDL/17-04-2013/PRO_1311 is saved successfully"

Output:

HDL/17-04-2013/PRO_1311

I tried googling, but unable to get the result. Pls suggest.

1
  • @user1787641 what have you tried on google. Commented Apr 17, 2013 at 10:33

4 Answers 4

0

try

String recordNumber = str.replaceAll(".*?(\\w+/\\d{2}-\\d{2}-\\d{4}/\\w+).*", "$1");
2
  • thanks for the reply.. its working.. it would be great if you had explained the same.. Commented Apr 17, 2013 at 12:04
  • $1 is reference to group #1, this is expr inside (). So it says replace input string with the part that matched expr in round brackets. Commented Apr 17, 2013 at 12:20
0

Something like:

"Purchase Order ([A-Z]+/\d{2}-\d{2}-\d{4}/[A-Z]+_\d+) is saved successfully"

This way you'll get what you need in the first capturing group.

Of course, this depends on the pattern of your purchase orders, you should read something about regexes.

0

Is there a particular reason you need to use a regex? It's better to avoid them if there's a more suitable alternative, for performance and readability reasons.

In this case it seems likely that the prefix and suffix are always the same length, so you can simply use String.substring to remove them. If the order ID is always prefixed by "Purchase Order ", and followed by " is saved successfully", then you can just trim 15 characters off the front and 22 characters off the back:

String extract = "Purchase Order HDL/17-04-2013/PRO_1311 is saved successfully";
String orderId = extract.substring(15, extract.length() - 22);

(If you want to be really clear about where these magic numbers come from, you could define them as e.g. private static final int PREFIX_LENGTH = "Purchase Order ".length();)

1
  • Hi. thanks for the reply.. the problem is record number position will vary. sometimes it will be displayed as "Purchase Order saved successfully : HDL/17-04-2013/PRO_1311" Commented Apr 17, 2013 at 11:56
0

Something like:

String s = "Purchase Order HDL/17-04-2013/PRO_1311 is saved successfully";
Pattern p = Pattern.compile("(?<=Purchase Order ).+?(?= is saved successfully)");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group());
}

This is a regular expression that matches anything in middle of the two phrases. The first parenthesis is the look behind string and the second is the look ahead string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.