I have a string abc="userId=123&billId=567&custId=890" How do I use regular expression in Java to return 567?
3 Answers
Assuming it is always the value of billId that you wish to extract, and that billId is always an integer:
\bbillId=(\d+)
Example:
Pattern pattern = Pattern.compile("\\bbillId=(\\d+)");
Matcher matcher = pattern.matcher(inputStr);
int billId = 0;
if(matcher.find())
billId = Integer.parseInt(matcher.group(1));

- 139,544
- 27
- 275
- 264
-
I am using this code Pattern p = Pattern.compile("bill_account_id=(\\d+)"); String[] result = p.split(myStr); for (int i=0; i
– Thunderhashy Aug 06 '11 at 03:23 -
This doesnt return me 567. How should I use regular expression in this case ? – Thunderhashy Aug 06 '11 at 03:24
Is this a query string? It sure looks like one. You have many possibilities to parse one and I'd easily go with one of those rather than a regex.
Take a look at the answers here: Parsing query strings on Android
Use split
example is this
String abc="userId=123&billId=567&custId=890"
String[] partsOfExpression = abc.split("&");
String bill = partsOfExpression[1];
String[] billExp = bill.split("=");
int billAmount = Integer.parseInt(billExp[1]);
This code is a bit clunky and can be refined a lot but basically it gives you the ful value every time as compared to taking a section of the string between two points or something of that nature.
you could also modify this method to get the value of any part of the string by using .equals, but what you are doing is up to you.
You could also look into substrings and other methods in the java Strings library.

- 251
- 1
- 5
- 15