1

My java regex is

Pattern compile = Pattern.compile("^((?:[^\\n]+\\n?)+)\\n*");
String a = "# clj-markdown\n\nA Clojure library designed to ... well, that part is up to you.\n\n## Usage\nFIX==ME==\n\n## License\n\nCopyright © 2015 FIXME\n\nDistributed under the Eclipse Public License either version 1.0 or (at\nyour option) any later version.\n";
System.out.print(compile.matcher(a));
System.out.print(compile.matcher(a).matches());

this output false,but I test in javascript can pass.

/^((?:[^\n]+\n?)+)\n*/.text(b)

how to resolve this problem?

may be this is java regex difference of javascript regex.

2
  • Try with Pattern.DOTALL -- not sure if that will work. Commented Apr 18, 2015 at 11:41
  • 1
    @Jongware it won't help since there isn't a dot in the op's regex. Commented Apr 18, 2015 at 12:04

1 Answer 1

1

Turn the in-between \n? to \n*, since \n? matches an optional newline character where \n* matches zero or more newline characters.

String a = "# clj-markdown\n\nA Clojure";
System.out.print(a.matches("^((?:[^\\n]+\\n*)+)\\n*"));

The part where your regex ^((?:[^\\n]+\\n?)+)\\n* fails is markdown\n\nA substring. ie, because of \n\n two newline characters.

(?:[^\\n]+\\n?) matches upto the markdown\n, and the next character in the input string is a newline character , when you make this regex to repeat one or more times (?:[^\\n]+\\n?)+ it would expect any character but not of \n immediately after matching the optional newline character. But there is a newline character following , so this makes the regex to fail.

matches method in java returns true only if the given regex matches the whole input string.

But test function in javascript will return true if the regex given matches from the start (partial or fullmatch but it must be from the start). It won't except full string match.

Example:

> /^[^\n]+\n/.test('foo\n\nbarbuz')
true
> /^[^\n]+\n/.test('\n')
false
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks,good job.but,you know why javascript can pass this regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.