Vinesh
Vinesh

Reputation: 943

Finding Decimal in a string

I am having a string like this:

Thank you for paying your Insurance bill of Rs 5896.48. Your transaction number for this payment is 981562359815. Your card will be debited on 2020-07-15.

I need to extract decimals of transaction number alone using regex. Count of decimals may vary time to time.

Pattern.compile("(?i)(transaction number *?)(.+?)(\\.)")

Using the above patter I tried to extract but I can't successful with this approach. Is there any efficient approach?

Upvotes: 0

Views: 122

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Assuming that there may be no dot (.) between the string transaction number and the number you're searching for, use

Pattern regex = Pattern.compile("(?i)transaction number [^.]*\\b(\\d+)\\.");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
} 

Explanation:

(?i)    # case insensitive matching mode
transaction\ number  # Match this literal text
[^.]*   # Match any number of characters except dots
\b      # Match the position at the start of a number
(\d+)   # Match a number (1 digit or more), capture the result in group 1
\.      # Match a dot

If you simply want to find the very first number after transaction number, then use

Pattern.compile("(?i)transaction number\\D*(\\d+)")

\D matches any character that is not a digit.

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

try this

 s = s.replaceAll(".* is (\\d+).*", "$1");

Upvotes: 1

Related Questions