Use regular expression to look for "%" [closed]

I'm programming in Java and I want to use regex to look for any data with a percent sign, e.g. 10%, 20%,30%,etc. I've tried a.matches("%")but that only returns true if the string matches exactly the percent sign. What should be the correct regular expression to use? Thanks

2

1 Answer

If you're just looking for a '%', then String.indexOf('%') would probably be faster and simpler than any regular-expression-based solution.

Considering regular expressions, the matches() function attempts to match the entire string to the pattern, as you've discovered. Matcher.find() will look for substrings within the string that match the pattern, for example:

Pattern pp = Pattern.compile("%");
Matcher mm = pp.matcher(someString);
if (mm.find()) { // someString contains a '%' ...
}

You Might Also Like