-1

I have such text:

120.65UAH Produkti Kvartal
5*14 14:24
Bal. 16603.52UAH

What I want to do: If this text contains "5*14", I need to get 16603.52 via one java reg exp.

this

and this

and this

I tried to create conditional regexp like this:

(5*14 ([\d\.*]+)UAH)
(5*14 d{2}:d{2} Bal. ([\d\.*]+))

etc

But no luck, can you please share your th

Community
  • 1
  • 1
Java Dude
  • 454
  • 6
  • 24
  • You've tagged this question with both Java and JavaScript. Which is it? They're not interchangeable. – Jordan Running Sep 07 '15 at 22:25
  • 2
    ["Java and Javascript are similar like Car and Carpet are similar."](http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java) – Derek 朕會功夫 Sep 07 '15 at 22:30
  • Try [`\b5\*14\b[\s\S]*?\b(\d+\.\d+)`](https://regex101.com/r/lI4vY9/1). This should work in both JS and Java (with appropriate escaping). If that does not work for you, please clarify your question (add more requirements, what is static what is dynamic in the input, etc.) – Wiktor Stribiżew Sep 07 '15 at 22:32
  • @Derek朕會功夫 I prefer "like ham and hamster." – Jordan Running Sep 07 '15 at 22:35

3 Answers3

2

You can use a regex like this:

(?=5\*14)[\s\S]*?(\d{5}\.\d{2})

Working demo

enter image description here

Update: you even don't need the look ahead, you can just use:

5\*14[\s\S]*?(\d{5}\.\d{2})
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • The alternative to the `[\s\S]` trick is to make `.` match newlines: `(?s)5\*14.*?(\d{5}\.\d{2})` – Andreas Sep 08 '15 at 00:18
0
(\d*\.\d\d)(?>\w*)$

will match a group on the last set of DDDDD.DD in the line. You will need to take the contents of the first matching group.

Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
0

If you have 5*14 before the float number you need to get, you can just use

(?s)\\b5\\*14\\b.*?\\b(\\d+\\.\\d+)

See demo. The value will be in Group 1. I also used Java escaping style.

Note that 5\*14 can match in 145*143 that is why I am using word boundaries \b. .*? with (?s) matches any number of any symbols but as few as possible. \d+\.\d+ matches simple float number (irrespective of the number of digits there are in it).

IDEONE demo:

String str = "120.65UAH Produkti Kvartal\n5*14 14:24\nBal. 16603.52UAH";
Pattern ptrn = Pattern.compile("(?s)\\b5\\*14\\b.*?\\b(\\d+\\.\\d+)");
Matcher matcher = ptrn.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Result: 16603.52

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563