I have a String, where only numbers and none, one or more percentages are allowed
so my regex would be: [\d+%], you can test it here
for java i have to transform it,
public static final String regex = "[\\d+\\%]";
and to test it i use this function
public static final String regex = "[\\d+\\%]";
public boolean validate(String myString){
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(myString);
if (!matcher.matches()) {
return false;
}else{
return true;
}
}
The regular expression is not working, also if i use
public static final String regex = "[\\d+%]";
Is there any good online tool for escaping a long regular expression for java?
A more advanced question:
the % should be only allowed if a minimum of one digit is in the String, only a % shouldn’t be allowed! And: numbers without a % are only allowed if the number of digits is exactly 8, not less (means: 1234567 is bad, but 12345678 is good)
Testcases:
- Bad:
%,(empty string),23b,-1,7.5,%5a,1,1234567 - Good:
12345678,23%,1%53%53,%7
Actually, that matches ONE character which may be a digit, a
+or a%.To match what you have described in words, you need something like this:
which matches a string containing at least one digit with optional percent signs. Note that the
%character is not a meta-character and hence doesn’t need to be escaped in the regex. It will match all of the following:and so on, but not just
%or any string that contains characters other than digits or%characterss.I’m not aware of one. But escaping wasn’t the reason your regex wasn’t working.
I think my regex above does that. And for the record, here is what it looks like as a Java String literal:
Unless you have TAB, NL, CR, etc characters in the regex , it is sufficient to just replace each individual
\with\\.