Hoang Nam
Hoang Nam

Reputation: 111

Regular expression to find money value

I have response text:

Cuoc no truoc -2.134VND. Cuoc phat sinh tam tinh den 31/08/2018:
3`2.666VND (da tru KM,goi cuoc...). TKFastpay: 0VND.Tra 01.Trang sau 02.Thoat\",15

i want get result is value of money before "VND" -> -2.134 and 32.666 and 0.

I have regex

String regex = "(?<![^=])([\\d]*)(?!$[VND])";

but its not work. Please help me!

Upvotes: 0

Views: 1070

Answers (5)

Leandro Keen Zapa
Leandro Keen Zapa

Reputation: 196

Try this simple regex

In Java

String regex = "(-?\\d*?\\.?\\d+)(?=VND)";

regex

(-?\d*?\.?\d+)(?=VND)

see regex sample

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163457

You could use a positive lookahead (?= and a word boundary after VND \b.

-?\d+(?:\.\d+)?(?=VND\b)

Regex demo

That would match

  • -? Optional minus sign (To also allow a plus, you could use an optional character class [+-]?
  • \d+ Match one or more digits
  • (?:\.\d+)? An optional non capturing group matching a dot and one or more digits
  • (?=VND\b) Positive lookahead that asserts what is on the right is VND

In Java:

-?\\d+(?:\\.\\d+)?(?=VND\\b)

Demo Java

Upvotes: 3

anubhava
anubhava

Reputation: 785481

You may use this regex with a lookahead:

[+-]?\d+\.?\d*(?=VND)

RegEx Demo

RegEx Details:

  • [+-]?: Match optional + or -
  • \d+\.?\d*: Match a floating point number or integer number
  • (?=VND): Assert that we have VND at next position

Java Code:

final String regex = "[+-]?\\d+\\.?\\d*(?=VND)";
final String string = "Cuoc no truoc -2.134VND. Cuoc phat sinh tam tinh den 31/08/2018:\n"
+ "32.666VND (da tru KM,goi cuoc...). TKFastpay: 0VND.Tra 01.Trang sau 02.Thoat\\\",15";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(0));
}

Upvotes: 2

KevinO
KevinO

Reputation: 4403

If I understand the requirement, then the regex, used in a repeated fashion, might be:

(-?)[\\d][\\d.]*(?=VND)

The idea being that you need at least one digit, followed by more digits or a decimal, then followed by VND.

A slightly improved approach would be to split the [.] to be between the digits, so: ((-?)[\d]+[.]?[\d]*)(?=VND)

Online Example

Upvotes: 1

Mohammadreza  Alagheband
Mohammadreza Alagheband

Reputation: 2230

Solution:

String regex = "(-?[0-9]+[\.]+[0-9]*)VND"

Description:

  1. You should create group before each and every VND string
  2. Inside the group first you should check whether minus sign available or not so whe have : -?
  3. the we need to capture every digits and we are expecting to have one or more : so [0-9]+
  4. there might be a dot sign (zero or one) in case of decimal . so we have [.]+
  5. again you might have another series of digits after decimal ( zero or more) point so : [0-9]*

Upvotes: 1

Related Questions