Home > Back-end >  Regex to parse percentage range from given string
Regex to parse percentage range from given string

Time:11-11

I was trying to form regex which should be able to extract percentage range from any String. For example- Adidas 30-60% Off on footwear,

I am able to extract 60% from this string using - \\b\\d (?:%|percent\\b) , But, this should work for both 56% as well as 30-60%.

Any help will be appriciaed.

CodePudding user response:

You can use

\b(?:\d [—–-])?\d (?:%|percent\b)

With fractions support it may look like

\b(?:\d (?:\.\d )?[—–-])?\d (?:\.\d )?(?:%|percent\b)

See the regex demo. Details:

  • \b - a word boundary
  • (?:\d (?:\.\d )?[—–-])? - an optional sequence of one or more digits followed with an optional sequence of . and one or more digits and then a dash
  • \d (?:\.\d )? - one or more digits followed with an optional sequence of . and one or more digits
  • (?:%|percent\b) - % or percent followed with a word boundary.

See a Java demo:

import java.util.regex.*;

class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "both 56% as well as 30-60%.";
        Pattern pattern = Pattern.compile("\\b(?:\\d [—–-])?\\d (?:%|percent\\b)");
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()){
            System.out.println(matcher.group()); 
        } 
    }
}

Output:

56%
30-60%

CodePudding user response:

public static void main(String[] args) {
        String line = "Adidas 30-60% Off";
        String pattern = "\\b[\\d|-] (?:%|percent\\b)";

        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(line);
        if (m.find( )) {
            System.out.println("Found value: "   m.group(0) );
        } else {
            System.out.println("NO MATCH");
        }
    }
  • Related