How can I write a method to check if string contains only numbers, letters, specific characters ( +_-/
) and only double backslashes ( \\\\
).
example:
a2b/\\
- false
d+sd\\\\ff
- true
I tried this:
stringExample.matches("^[a-z-A-Z-0-9 +_-/]+");
...but it doesn't match a double backslash ( \\\\
).
Since backslashes are generally used as the escape character, they have to be escapsed as well via a \\\\
to represent a single slash, so two consecutive backslashes would use \\\\\\\\
.
So for your expression to allow those characters and only sets of two backslashes, you could use :
stringExample.matches("^([\\w\\s+\\-/]|(\\\\\\\\))+$");
This can be explained as follows :
^ # Beginning of expression
( # Beginning of group
[\\w\\s+\\-/] # Match any alphanumeric or underscore (\w), space (\s), or +, - or \
| # OR
(\\\\\\\\) # An explicit double-slash
) # End of group
+ # Allow one or more instances of the previous group
$ # End of expression
\\ is a special character. It has functionality in regex (escaping). This means that you need to escape it in order to capture it as it's own character.
\\\\ would mean '\\' as a character
This might help:
private static void checkdoubleSlash(String a) {
if(a.contains("\\\\"))
System.out.println("True");
else
System.out.println("False");
}
First of all, the pattern as you wrote it doesn't compile:
^[a-z-A-Z-0-9 +_-/]+
Because _-/
is interpreted as a range, but that's invalid. It's better to move the -
to the end, to make it not be a range:
^[a-z-A-Z-0-9 +_/-]+
And also remove the duplicated -
^[a-zA-Z0-9 +_/-]+
Next, notice that [...]
is for single characters. And you don't to allow single \\
, only double \\\\
, so that's a two-character pattern. To achieve this, the regular expression should be something like:
^([a-zA-Z0-9 +_/-]|double-backslash)+
I wrote "double-backslash there because this needs a bit of extra explanation. To write that, is not simply \\\\
, because in Java strings you need to escape backslashes, so \\\\\\\\
. And in regular expressions, you need to escape them again. So the final regular expression you need is:
^([a-zA-Z0-9 +_/-]|\\\\\\\\)+
With some unit tests:
public boolean testMatch(String s) {
return s.matches("^([a-zA-Z0-9 +_/-]|\\\\\\\\)+");
}
@Test
public void should_match_string_with_double_backslash() {
assertTrue(testMatch("d+sd\\\\ff"));
}
@Test
public void should_not_match_string_with_single_backslash() {
assertFalse(testMatch("a2b/\\"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.