1

I am trying to test that a string is alphanumeric, can only contain _ and -, and does not contain any double hyphens. So, I tested my regex phrase in the UI using the following format:

/^(?!.*--)[a-zA-Z0-9_-]+$/.test("myString"); //true
/^(?!.*--)[a-zA-Z0-9_-]+$/.test("my--String"); //false

However, when I try to implement this into my java back-end, it is failing the check.

Pattern pattern = Pattern.compile("(?!.*--)[a-zA-Z0-9_-]+");

Is the format for the pattern object incorrect?

matisetorm
  • 857
  • 8
  • 21
user3334871
  • 1,251
  • 2
  • 14
  • 36
  • Is it Java or JavaScript? – Andrew Li Jun 30 '16 at 23:07
  • I was testing the pattern originally in my console, so JavaScript, and the pattern I created was correctly checking for the required syntax. I tried to copy the pattern into my java code to implement a Pattern object, but it fails the check in my java code. – user3334871 Jun 30 '16 at 23:08
  • Could it be just because you did not add the boundary matchers in your code? Should be like this : `Pattern.compile("^(?!.*--)[a-zA-Z0-9_-]+$");` – swlim Jun 30 '16 at 23:15
  • @SWLim hmm, could be. I thought java doesn't need the perl starting and anchor tags for regex? – user3334871 Jun 30 '16 at 23:16
  • Possible duplicate of [Regular expression to match line that doesn't contain a word?](http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word) – TemporalWolf Jun 30 '16 at 23:16
  • 1
    I don't think it's just for Perl. Here's the doc for Java's boundary matchers https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html Btw, for alpha numeric, you could just do [\w] as well, instead of [a-zA-Z0-9] – swlim Jun 30 '16 at 23:17
  • @SWLim Thanks, I will try that now. And TemporalWolf, The pattern I have works in Perl, I am just having difficulty applying the pattern to my Java Pattern object. – user3334871 Jun 30 '16 at 23:19
  • With the given pattern `pattern.matcher("myString").matches()` will be evaluated to `true` and `pattern.matcher("my--String").matches()` will be evaluated to `false`. Your pattern is correct, but maybe the following code is incorrect. – howlger Jul 02 '16 at 10:28

0 Answers0