-2

I am using this pattern to check

public static final Pattern VALID_FIRST_CHARACTERS = Pattern.compile("^[\\ \\'\\-]");

public boolean isValidFirstChar(String name) {
    if (VALID_FIRST_CHARACTERS.matcher(name).matches()) {
        return true;
    }
    return false;
}

no luck, can somebody help me please ?

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
Happy
  • 169
  • 1
  • 4
  • 10
  • What do you think the pattern literal `^[\\ \\'\\-]` represents? Why do you think so? – Sotirios Delimanolis Jun 24 '15 at 15:56
  • Also why aren't you using `String#startsWith`? – Sotirios Delimanolis Jun 24 '15 at 15:57
  • I am using public static final Pattern VALID_NAMEFIELD_CHARACTERS = Pattern .compile("([a-zA-Z àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ\\ \\'\\-])*"); and it is working fine just not able check the first character – Happy Jun 24 '15 at 15:58
  • @SotiriosDelimanolis I need to do all 3 validation at one time if I use string start with I have to use 3 time – Happy Jun 24 '15 at 16:01
  • Why do you _have to_? Do you think it's faster, more efficient? Why do you think so? – Sotirios Delimanolis Jun 24 '15 at 16:02
  • @SotiriosDelimanolis because I need it – Happy Jun 24 '15 at 16:10
  • @SotiriosDelimanolis he doesn't `"Why do you have to?"` have to use regex but the code is cleaner if he does...I don't think it has anything to do with being faster or more efficient just cleaner looking code. Better readability... – brso05 Jun 24 '15 at 16:12

1 Answers1

1

You can change yours like this and it will work:

public static void main(String[] args) throws FileNotFoundException {
    System.out.println(isValidFirstChar("-test"));
    System.out.println(isValidFirstChar("\\test"));
    System.out.println(isValidFirstChar("\'test"));
    System.out.println(isValidFirstChar("test"));
}
public static final Pattern VALID_FIRST_CHARACTERS = Pattern.compile("^[\\\\ \\' \\-].*");

public static boolean isValidFirstChar(String name) {
    if (VALID_FIRST_CHARACTERS.matcher(name).matches()) {
        return true;
    }
    return false;
}

The result of this is:

true
true
true
false

You must escape the \\ for java but also for regex that is why you need \\\\ this will become \\ when translated for the regex...

The .* on the end means match anything after...So it starts with \ or ' or - and is followed by anything.

brso05
  • 13,142
  • 2
  • 21
  • 40
  • thanks for your reply its working I just needed hyphens (-), apostrophes (‘), and spaces ( ) to be matched so I changed it to public static final Pattern VALID_FIRST_CHARACTERS = Pattern .compile("^[' -].*"); working fine now thanks @brso05 – Happy Jun 24 '15 at 16:08