Home > Software design >  Match Path using Regex in Java
Match Path using Regex in Java

Time:10-24

I'm trying to match the pattern path which follows: secret/roles/[can be anything]/dev/[Variable]/[can be additional child paths or just empty]

I tried the following:

String Vairable = "john";
String RegularExpression = "(secret/roles)?(/[a-zA-Z0-9_.-])?(/dev)?(/"   Variable   ")?(/[a-zA-Z0-9_.-] ) /?"; 

but it doesn't filter the Variable part and basically captures all the child paths under secret/roles/...

CodePudding user response:

Using matches, you can use either

String RegularExpression = "secret/roles/[^/] /dev/" Pattern.quote(Vairable) "/.*";

Or

String RegularExpression = "secret/roles/[^/] /dev/" Pattern.quote(Vairable) "/[^/]*";

In the first case, anything can go after Vairable and a backslash, in the latter, only one subpart is allowed, no / chars can appear after that backslash.

The Pattern.quote() is added to escape any special regex metacharacters that may occur in the Vairable variable.

  • Related