【发布时间】:2017-11-28 11:21:35
【问题描述】:
The dot language 有一些标识符规则。我想制作一个符合 groovy 中第一个的正则表达式。规则是
任何不以数字开头的字母 ([a-zA-Z\200-\377]) 字符、下划线 ('_') 或数字 ([0-9]) 字符串;
我想做这样的事情
[_a-zA-Z\200-\377][_0-9a-zA-Z\200-\377]*
但是 groovy 抱怨 \200-\377。我怎样才能使这个正则表达式 groovy 兼容?
编辑:一些额外的代码
String getId(String id) {
if(id ==~ /[_a-zA-Z\200-\377][_0-9a-zA-Z\200-\377]*/) {
return id
} else {
return "\"$id\""
}
}
还有错误
Illegal/unsupported escape sequence near index 9
[_a-zA-Z\200-\377][_0-9a-zA-Z\200-\377]*
编辑 2:这是 spock 测试
@Unroll('"#id" converts to "#expected"')
def 'ids are converted to dot ids'() {
expect:
graphviz.getId(id) == expected
where:
id | expected
'_' | '_'
'a' | 'a'
'A' | 'A'
'a9' | 'a9'
' ' | '" "'
'234' | '"234"'
'two words' | '"two words"'
}
【问题讨论】:
-
我相信 groovy 依赖于 Java 的正则表达式来支持它的正则表达式。 docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html 那么你试过
\0200-\0377吗? (我猜\200-\377是八进制值,就像在 C/C++ 中一样?)