Home > Blockchain >  How to check if the source path has regex / wildcard available?
How to check if the source path has regex / wildcard available?

Time:04-29

Users can provide any path with wildcard or regex. If they provide that, I need to identify that it is not a full static path.

var sourcePath: Array(String) = Array("/user/Orders/201507{2[7-9],3[0-1]}*")

I am writing below code and I guess I need to check for all the chars like ? { ^ etc. Is there any better way?

if (sourcePath.trim.toLowerCase().indexOf("*") > 0) 
{
  println("Source path has wildcard/regex")
}
else
{ 
  println("it is a static path, having no wildcard or regex")
}

CodePudding user response:

After correcting the array initialization and the operations you performed, your code will produce the solution in the following way:

var sourcePath: Array(String) = Array("/user/Orders/201507{2[7-9],3[0-1]}*") 

for(path <- sourcePath){

    if( path.trim.toLowerCase().indexOf("*") > 0 ) {
        println("source path has wildcard/regex")
    }

    else {
        println("it is a static path, having no wildcard or regex")
    }
}

Output:

source path has wildcard/regex

There are other ways to perform the same task as above. Some of them are provided below:

Using Regex:

import scala.util.matching.Regex 

val pattern = new Regex("[*]")    //the regex/wildcard you want to check

for(path <- sourcePath){

    if( (pattern findAllIn path).mkString("").length > 0 ) {
        println("Source path has wildcard/regex")
    }

    else {
        println("it is a static path, having no wildcard or regex")
    }
}

Using matches():

for(path <- sourcePath){

    if( path.matches(".*/*") ) {  
        //Here,'.*' is required syntax and '/' is an escape character in this case
        println("Source Path has wildcard/regex")
    }

    else {
        println("it is a static path, having no wildcard or regex")
    }
}

If you are looking for a better way to do this, string functions (optimized) perform better than regular expressions in most cases. So, in this case, you can go ahead with either indexOf() or matches().

You can also refer to the following for a few additional ways.

Scala check if string contains no special chars

  • Related