Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to escape Unicode escapes in Groovy's /pattern/ syntax
    primarykey
    data
    text
    <p>The following Groovy commands illustrate my problem.</p> <p>First of all, this works (<a href="http://lotrepls.appspot.com/?language=Groovy&amp;script=%20%22%5Cn%22.matches%28%22%5Cu000A%22%29;?language=Groovy&amp;script=print%20%22a%22.matches%28/%5Cu0061/%29" rel="nofollow noreferrer">as seen on lotrepls.appspot.com</a>) as expected (note that <code>\u0061</code> is <code>'a'</code>).</p> <pre><code>&gt;&gt;&gt; print "a".matches(/\u0061/) true </code></pre> <p>Now let's say that we want to match <code>\n</code>, using the Unicode escape <code>\u000A</code>. The following, using <code>"pattern"</code> as a string, behaves as expected:</p> <pre><code>&gt;&gt;&gt; print "\n".matches("\u000A"); Interpreter exception: com.google.lotrepls.shared.InterpreterException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, Script1.groovy: 1: expecting anything but ''\n''; got it anyway @ line 1, column 21. 1 error </code></pre> <p>This is expected because in Java at least, Unicode escapes are processed early (<a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.3" rel="nofollow noreferrer">JLS 3.3</a>), so:</p> <pre><code>print "\n".matches("\u000A") </code></pre> <p>really is the same as:</p> <pre><code>print "\n".matches(" ") </code></pre> <p>The fix is to escape the Unicode escape, and let the regex engine process it, as follows:</p> <pre><code>&gt;&gt;&gt; print "\n".matches("\\u000A") true </code></pre> <p>Now here's the question part: how can we get this to work with the Groovy <code>/pattern/</code> syntax instead of using string literal?</p> <p>Here are some failed attempts:</p> <pre><code>&gt;&gt;&gt; print "\n".matches(/\u000A/) Interpreter exception: com.google.lotrepls.shared.InterpreterException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, Script1.groovy: 1: expecting EOF, found '(' @ line 1, column 19. 1 error &gt;&gt;&gt; print "\n".matches(/\\u000A/) false &gt;&gt;&gt; print "\\u000A".matches(/\\u000A/); true </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload