Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match the forward slash using regex

Tags:

java

regex

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

like image 205
vinoth.mohan Avatar asked Oct 14 '16 08:10

vinoth.mohan


People also ask

How do you handle forward slash in regex?

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.

Is forward slash a regex character?

The above example has a forwardslash that must be included in the capture value, but a forward slash is a regex special character.

How do I match a forward slash in regex Perl?

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.

How do you match a slash in a regular expression in Java?

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.


1 Answers

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

like image 193
Zabuzard Avatar answered Oct 13 '22 15:10

Zabuzard