Reputation: 513
I need to separate a string like this:
C-USD10.00_FRIES AND BURGUER_USD15.00
In groups like this
segment = first_char;
subtotal_currency = after-next_3_chars;
subtotal = digits_up_to_;
description = text_up_to_;
total_curency = next_3_char;
total = last_digits;
I guess that one way to represent it is this:
(?P<segment>[A-Z])-(?P<scurr>[A-Z]{3})(?P<subtotal>\d+(?:,\d{1,2})?)_(?<desc>^\s*[a-zA-Z,\s]+\s*$)_(?P<curr>[A-Z]{3})(?P<total>\d+(?:,\d{1,2})?)
The expected result would be:
segment = "C";
subtotal_currency = "USD";
subtotal = 10.00;
description = "FRIES AND BURGUER";
total_curency = "USD";
total = 15.00;
How can I make use of regular expressions in java to make the division of the string in that way?
By the way, I have to make this job for many types of strings... so I guess using regular expressions will help me a lot.
Upvotes: 1
Views: 95
Reputation: 789
Regexes are in the java.util.regex package.
Looks like you have the right idea. Based on the documentation for the Pattern and Matcher classes, the only thing you need to remove from your pattern is the Ps between the ? and the < for the named group, something like this:
(?<segment>[A-Z])-(?<scurr>[A-Z]{3})(?<subtotal>\d+(?:,\d{1,2})?)_(?<desc>^\s*[a-zA-Z,\s]+\s*$)_(?<curr>[A-Z]{3})(?<total>\d+(?:,\d{1,2})?)
Create your Pattern object, then call .matcher() on the String to get the Matcher. Then you can extract the info from the Matcher with the .group(String) method.
You could easily make the system generic, but helpful to your domain.
Upvotes: 1
Reputation: 67968
(?P<segment>[A-Z])-(?P<scurr>[A-Z]{3})(?P<subtotal>\d+(?:[.,]\d{1,2})?)_(?<desc>\s*[a-zA-Z,\s]+\s*)_(?P<curr>[A-Z]{3})(?P<total>\d+(?:[.,]\d{1,2})?)
^^ ^^
Try this.See demo.
https://regex101.com/r/fX3mH8/2
Issues:
1)added .
along with ,
.
2)Removed ^$
from middle string.
Upvotes: 0