如何在Scala中从字符串中删除所有结尾的反斜杠?

时间:2018-08-10 15:05:44

标签: regex scala

我想从字符串中删除所有结尾的反斜杠('\')。

例如:

"ab"       -> "ab" 
"ab\\\\"   -> "ab"
"\\\\ab\\" -> "\\\\ab"
"\\"       -> ""

我能够使用下面的代码来执行此操作,但无法处理字符串仅带有斜杠的情况。请让我知道是否可以通过其他正则表达式来实现。

val str = """\\\\q\\"""
val regex = """^(.*[^\\])(\\+)$""".r
str match  {
  case regex(rest, slashes) => str.stripSuffix(slashes)
  case _ => str
}

5 个答案:

答案 0 :(得分:1)

虽然不是正则表达式,但我建议使用一种更简单的解决方案:str.reverse.dropWhile(_ == '\\').reverse

答案 1 :(得分:1)

不使用正则表达式,但是可以使用String.lastIndexWhere(p: (Char) ⇒ Boolean)来获取不是'\'的最后一个字符的位置,以便在此字符之前进行子串化:

str.substring(0, str.lastIndexWhere(_ != '\\') + 1)

答案 2 :(得分:1)

将我的评论作为答案。这应该可以删除所有结尾的反斜杠:

str = str.replaceFirst("\\\\+$", "");

\\\\+匹配1个以上的反斜杠(在Java / Scala中,单个反斜杠作为\\\\输入)。

答案 3 :(得分:1)

如果由于某种原因您致力于正则表达式解决方案,那么可以做到。

//
// AViewController.swift
//
class AViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gotoB", let bController = segue.destination as? BViewController {
            // Give B a chance to finish loading before using its outlets
            bController.loadViewIfNeeded()
            bController.textField.text = label.text
            bController.delegate = self
        }
    }
}

extension AViewController: BViewControllerDelegate {
    // B says that it has ended. We now update the label in A
    func bViewControllerDidEnd(_ controller: BViewController, textValue: String) {
        label.text = textValue
    }
}

//
// BViewController.swift
//
protocol BViewControllerDelegate {
    // For delegate methods, it's customary to pass in the object that triggers this delegate
    // (the BViewController), in case you need to make use of its other properties
    func bViewControllerDidEnd(_ controller: BViewController, textValue: String)
}

class BViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!
    var delegate: BViewControllerDelegate?

    @IBAction func goBackToA(_ sender: Any) {
        // Tell the delegate that "I'm done"
        delegate?.bViewControllerDidEnd(self, textValue: textField.text!)

        // Dismiss B, not segue to another instance of A
        self.dismiss(animated: true)
    }
}

答案 4 :(得分:0)

您可以使用slice函数进行相同操作

str.slice(0,str.lastIndexWhere(_ != '\\')+1)
相关问题