0

How to get ricCode:.ABC from following string. My matcher is

Matcher matcher = Pattern.compile("ricCode:([A-Za-z]+),$").matcher(str);

String str = "{AMX:{ricCode:.ABC,indexDetailEnable:true,price:20,648.15,netChange:<spanclass="md-down">-41.09</span>,percentChange:<spanclass="md-down">-0.20%</span>,tradeDate:17/04/05,tradeTime:16:40,chartDate:17/04/05,chartTime:16:40}";

What is missing in the regex?

1 Answer 1

1

Change your regex from this:

ricCode:([A-Za-z]+),$

to this:

ricCode:([A-Za-z.]+)(?=,)

Your original regex would only allow alphabetic characters after ricCode:, but your example has a period . character. Also you were matching the , character, but this would also include the comma in your match, you dont want this - so I added a positive lookahead for the comma so it looks for it there but does not match it. Finally you had the $ character at the end of your regex which matches the end of the string, you dont want to look for the end of the string immediately after the comma, so I removed it.

It helps to use regexr.com to test out your expression.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for quick response. I have added and trying to print substring but getting IllegalArgumentError. I am trying to print getting IllegalArgumentException. Matcher matcher = Pattern.compile("ricCode:([A-Za-z.]+)(?=,)").matcher(test); while (matcher.find()) { String str = test.substring(matcher.start("ricCode:"),matcher.end()); System.out.println("value :: "+str); }
Sorry I was printing it in wrong way. System.out.println("value :: "+ matcher.group()) correct way. Thanks a lot
how will be the regex to get anything after ricCode: till comma ?
You could use this: (?<=ricCode:)[^,]+(?=,), it uses positive lookbehind to find ricCode: but doesnt include it in the match, then looks for 1 or more characters that are not , and then positive lookahead for your ,
@user2811650 if my answer is right and helped you i'd appreciate if you could mark it as the accepted answer and upvote. Thanks!

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.