Sava :
Somebody can explain how to use regular expression in java. I have few strings 3 :- N, ‘V—g'ufi “ ‘L Total: 13-70 "0- 1‘ i
and r _._A_ ,,1 Total: $13.70 i- T«
. I need to extract Total: with sum after it: Ex of expected output Total: 13-70, Total: $13.70
. I tried to use following code... But as I understand, it will not catch symbols, such as $.-
Pattern p = Pattern.compile("Total: \\d+");
Matcher m = p.matcher(result);
while (m.find()) {
System.out.println(m.group());
}
Wiktor Stribiżew :
You may use
Total:\s*\$?\d+(?:[-.]\d+)?
See the regex demo.
Details
Total:
- a literal substring\s*
- 0+ whitespaces\$?
- an optional$
char\d+
- 1+ digits(?:[-.]\d+)?
- an optional non-capturing group matching 1 or 0 occurrences of:[-.]
- either-
or.
\d+
- 1 or more digits.
In Java:
Pattern p = Pattern.compile("Total:\\s*\\$?\\d+(?:[-.]\\d+)?");
If you need to extract the value use a capturing group round the pattern you need to extract (here, \$?\d+(?:[-.]\d+)?
, for example) and access the group value like
Pattern p = Pattern.compile("Total:\\s*(\\$?\\d+(?:[-.]\\d+)?)");
Matcher m = p.matcher(result);
while (m.find()) {
System.out.println(m.group(1));
}