我正在使用Groovy处理String Calculator code kata。
有许多方案可以解决以实现解决方案:
我有:
//;\n1;2;3
//#\n1#2#3
//+\n1+2+3
//*\n1*2*3
//?\n1?2?3
我想:
1,2,3
我的实施:
String numbers = "//;\n1;2;3"
numbers.find(/\/\/\S[\n]/) { match ->
def delimeter = match[2]
numbers = numbers.minus(match).replaceAll(delimeter, ",")
}
使用此解决方案我解决了第一个和第二个表达式,但我不知道如何解决其他表达式。
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
问题是我们还必须考虑与+
,*
或?
答案 0 :(得分:1)
最后我有解决方案:
String numbers = "//+\n1+2+3"
numbers.find(/(?s)\/\/(.*)\n/) { match ->
def delimeter = match[1] // also match[0][2]
numbers = numbers.minus(match[0]).replace(delimeter, ",")
}
重点(?s):
在dotall模式下,表达式。匹配任何字符,包括行终止符。默认情况下,此表达式与行终止符不匹配。 Dotall模式也可以通过嵌入式标志表达式(?s)启用
但问题确实在这里:.replace(delimeter, ",")
答案 1 :(得分:0)
//(.)\n(\d)\1(\d)\1(\d)
需要使用链接。 (。) - 数学thiw任何字符,\ 1 - 数学thiw字符\
对于下一个示例,您可以应用此项://\[(.*?)\]\\n(\d)\1(\d)\1(\d)
它数学thiw
// [的 *] \ N1 强> 2 ** 3
最后://\[(.*?)\]\[(.*?)\]\\n(\d)\1(\d)\2(\d)
// [* ] [%%] \ N1 * 2 %% 3
最后:
//\[(.*?)\](?:\[(.*?)\])?\\n(\d)\1(\d)(?:\2|\1)(\d)
我认为它可以发挥作用 P.S :( \ d)你可以替换你想要的东西。我认为你需要(\ d *)