我想匹配在scala中使用匹配的數學運算。因此,該函數將能夠匹配,如「5 + 2」或「LOG10」或任何字符串「10^5」等,但比賽一直未能爲各個類型的表達式在scala中使用正則表達式匹配數學運算
def isValid(expression:String):Boolean={
val number = """((\-|\+)?[0-9]+\.?[0-9])*"""
val operation = """([\+,\-,*,/,C,P])"""
val functions = """(log|ln|sin|cos|tan|arc sin|arc cos|arc tan|sec|csc|cot)"""
val powers = """\^"""+number
val arithmeticExpression = (number + operation + number).r
val functionExpression = (functions + number).r
val powerOperation = (number + powers).r
val stringToTest: Regex = ("""(""" +arithmeticExpression+"""|"""+functionExpression+"""|"""+powerOperation+""")""").r
expression match {
case arithmeticExpression(s) => true
case functionExpression(s) => true
case powerOperation(s)=>true
case _ => false
}
}
println(isValid("1+4").toString)
但是如果我匹配對於一般的表情,我得到預期的輸出:
def isValid(expression:String):Boolean={
val number = """(\-|\+)?[0-9]+\.?[0-9]*"""
val operation = """[\+,\-,*,/,C,P]"""
val functions = """(log|ln|sin|cos|tan|arc sin|arc cos|arc tan|sec|csc|cot)"""
val power = """\^"""+number
val arithmeticExpression = number+operation+number
val functionExpression = functions+number
val powerExpression = number+power
val validExpression = """(""" +arithmeticExpression+"""|"""+functionExpression+"""|"""+powerExpression+""")"""
validExpression.r.findFirstIn(expression) match {
case Some(`expression`) => true
case None => false
}
有網站嘗試正則表達式,這是痛苦的看看和撰寫。如果有一個庫你可以在REPL中加載來拉開正則表達式等,那將會很好。另外,如果你對它們不感興趣,可以使用'case r(_ *)=>'忽略匹配組。 –
是的括號混淆了表達式。謝謝! – Dguye