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.
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.
try
String recordNumber = str.replaceAll(".*?(\\w+/\\d{2}-\\d{2}-\\d{4}/\\w+).*", "$1");
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.
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();
)
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.