javaregexurl-validation

URL has to have # in it


I have problem in creating a regex which has to accept only those URL's which have # in it and neglect others. I'm using urlValidator and it has a RegEx which allows URL's without # in them. can someone help me with buliding a RegEx.

I have problems with the RegEx. just help me in building a RegEx which would validate only those URL's which have # in it

This is my code

import org.apache.commons.validator.routines.RegexValidator;
import org.apache.commons.validator.routines.UrlValidator;


public class TestClass {

    public static void main(String[] args) {
          String url = "https://www.testforregex.com/test";
          String[] schemes = {"#([^\\?|\\/|$]*)"};
          RegexValidator regex= new RegexValidator(schemes);
          UrlValidator urlValidator = new UrlValidator(regex,0);
          System.out.println(urlValidator.isValid(url));

      }

 }

Solution

  • For checking if a string contains a certain character, using regex is a little overkill. You could just use String.contains(). So in your case:

    boolean isValid = url.contains("#");