1

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

Paul
  • 139,544
  • 27
  • 275
  • 264
Thunderhashy
  • 5,291
  • 13
  • 43
  • 47

3 Answers3

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));
Paul
  • 139,544
  • 27
  • 275
  • 264
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

Community
  • 1
  • 1
Kris
  • 1,789
  • 3
  • 18
  • 27
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.

Andy
  • 251
  • 1
  • 5
  • 15