I am a newbie in java regex. I would like to know how to extract numbers or float numbers before %
. For example:
"Titi 10% Toto and tutu equals 20X"
"Titi 10.50% Toto and tutu equals 20X"
"Titi 10-10.50% Toto and tutu equals 20X
"Titi 10sd50 % Toto and tutu equals 20X
"Titi 10-10.50% or 10sd50 % Toto and tutu equals 20X
Output :
10
10.50
10-10.50
10sd50
10-10.50;10sd50
My idea is to replace all before and after "space + number(% or space%)"
by ;
in order to extract all values or group values before %
. I tried to use that: replaceAll("[^0-9.]+|\\.(?!\\d)(?!\\b)\\%",";");
= NO SUCCESS
How can I do it?
You can do as follows:
%
) of each match elements with BlankA java samples is given :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
final String regex = "\\d+(\\.?\\d+)?(\\+|\\-|sd)?(\\d+(\\.?\\d+)?)?[ ]*%";
final String test_str = "\"Titi 10% Toto and tutu equals 20X\"\n"
+ "\"Titi 10.50% Toto and tutu equals 20X\"\n"
+ "\"Titi 10-10.50% Toto and tutu equals 20X\n"
+ "\"Titi 10sd50 % Toto and tutu equals 20X\n"
+ "\"Titi 10-10.50% or 10sd50 % Toto and tutu equals 20X";
final Pattern pattern = Pattern.compile(regex);
for(String data : test_str.split("\\r?\\n")) {
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
System.out.print(data.substring(matcher.start(), matcher.end()-1) + " ") ;
}
System.out.println();
}
}
}
The above code gives :
10
10.50
10-10.50
10sd50
10-10.50 10sd50
You can do anything with these data. You can see the Explanations : Regex101
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments