2012-11-27 147 views
0

我奮力來連接兩個文本消息到Scala中使用正則表達式一個單一的文本字符串Scala的正則表達式用雙引號

original message = "part1 "+" part2" 
original message = "part1 " + " part2" 
original message = "part 1 "+ " part2" 

concatenated message = "part1 part2" 

我現在用的就是以下(此代碼來替換至少應+標誌與空)

val line:String = """"text1"+"text2"""" //My original String which is "text1"+"text2" 
val temp_line:String = line.replaceAll("\\+","") 
println(temp_line) 

它工作正常,結果「text1」「text2」。有沒有辦法使用正則表達式得到輸出「text1 text2」?

請幫忙。在此先感謝

+10

這真的不清楚。信息中是否有引號和加號?連接的消息是你想要產生的,而不管其他空間和東西(和引號)在其他?你想讓它工作到兩個,還是應該用一個或三個做一些明智的事情?你是否需要完全匹配單詞'part',或者你是在說明兩者的文本必須匹配,還是可以是任意文本? –

+0

是的。原始郵件中有加號和引號。所需的結果將是用引號括起來的單個文本,這將引發原始消息中所有文本的內容。我希望正則表達式也可以爲一個或三個工作。 Part1和Part2是可以是任意文本的示例文本。感謝您看到這個 – yalkris

+0

你的問題讓我感到困惑,因爲這與正則表達式沒有任何關係...... – Dylan

回答

1

這實在不是對正則表達式的理想的問題,但是沒關係:

val Part = """"([^"]*)"(.*$)""".r // Quotes, non quotes, quotes, then the rest 
val Plus = """\s*\+\s*(.*)""".r  // Plus with optional spaces, then the rest 

def parts(s: String, found: List[String] = Nil): String = s match { 
    case Part(p,rest) => rest match { 
    case "" => (p :: found).map(_.filter(c => !c.isWhitespace)).reverse.mkString(" ") 
    case Plus(more) => parts(more, p :: found) 
    case x => throw new IllegalArgumentException(s"$p :$x:") 
    } 
    case x => throw new IllegalArgumentException(s"|$x|") 
} 

這只是一塊需要輸入字符串開片;如果你想看看它是如何工作的,你可以添加printlns。 (請注意,+是正則表達式中的一個特殊字符,因此您需要將其轉義以匹配它。)

scala> parts(""""part1 "+" part2"""") 
res1: String = part1 part2 

scala> parts(""""part1 " + " part2"""") 
res2: String = part1 part2 

scala> parts(""""part 1 "+ " part2"""") 
res3: String = part1 part2 
+0

雖然這有點複雜,但工作。我研究了一個使用split和replaceAll的解決方案,它更易於閱讀和編輯。儘管如此,您的解決方案對於我的問題是理想的。謝謝。 – yalkris