1

I have a string abc="userId=123&billId=567&custId=890" How do I use regular expression in Java to return 567?

3 Answers 3

3

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));
Sign up to request clarification or add additional context in comments.

2 Comments

I am using this code Pattern p = Pattern.compile("bill_account_id=(\\d+)"); String[] result = p.split(myStr); for (int i=0; i<result.length; i++) System.out.println(result[i]); }
This doesnt return me 567. How should I use regular expression in this case ?
2

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

2 Comments

No it is not a query string. It is just a random url in a html
If it's part of a url then it's a query string.
0

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.

Comments

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.