How to use regex to detect and has the forward slash in path. Also with numbers
Example String str = "/urpath/23243/imagepath/344_licensecode/" I want to use regex to make sure the path is match for numbers with forward slash. the format match must like this "/23243/"
Any idea guys?
Thanks
The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.
The above example has a forwardslash that must be included in the capture value, but a forward slash is a regex special character.
If you want to match a pattern that contains a forward slash (/) character, you have to escape it using a backslash (\) character. You can also use a different delimiter if you precede the regular expression with the letter m , the letter m stands for match.
Regular Expressions, Literal Strings and BackslashesThe regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That's right: 4 backslashes to match a single one. The regex \w matches a word character.
You need to escape the special character /
by using \
. However, \
also is the escaping character used by Java, but you want to pass the symbol itself to Regex, so it escapes for Regex. You do so by escaping the escape symbol with \\
. So in total you will have \\/
for the slash.
Use this snippet:
String input = ...
Pattern pattern = Pattern.compile("\\/23243\\/");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Does match!");
} else {
System.out.println("Does not match!");
}
You can try the Regex itself at regex101: regex101/RkheRs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With