【问题标题】:scala regex group matching and replacescala 正则表达式组匹配和替换
【发布时间】:2012-11-23 13:52:03
【问题描述】:
val REGEX_OPEN_CURLY_BRACE = """\{""".r
val REGEX_CLOSED_CURLY_BRACE = """\}""".r
val REGEX_INLINE_DOUBLE_QUOTES = """\\\"""".r
val REGEX_NEW_LINE = """\\\n""".r

// Replacing { with '{' and } with '}'
str = REGEX_OPEN_CURLY_BRACE.replaceAllIn(str, """'{'""")
str = REGEX_CLOSED_CURLY_BRACE.replaceAllIn(str, """'}'""")
// Escape \" with '\"' and \n with '\n'
str = REGEX_INLINE_DOUBLE_QUOTES.replaceAllIn(str, """'\"'""")
str = REGEX_NEW_LINE.replaceAllIn(str, """'\n'""")

有没有更简单的方法来分组和替换所有这些{,},\",\n

【问题讨论】:

    标签: regex scala replace regex-group


    【解决方案1】:

    您可以像这样使用正则表达式组:

    scala> """([abc])""".r.replaceAllIn("a b c d e", """'$1'""")
    res12: String = 'a' 'b' 'c' d e
    

    正则表达式中的括号允许您匹配它们之间的字符之一。 $1 被正则表达式中括号之间的内容替换。

    【讨论】:

    • 由于他的序列是多字符的(有时),我认为交替会更好。
    • $0 实际上绑定到整个匹配字符串。 $1 绑定到第一个匹配组。在这种情况下,它们碰巧是相同的,因为第一个匹配组包含整个模式。
    【解决方案2】:

    您可以使用括号创建一个捕获组,$1 在替换字符串中引用该捕获组:

    """hello { \" world \" } \n""".replaceAll("""([{}]|\\["n])""", "'$1'")
    // => java.lang.String = hello '{' '\"' world '\"' '}' '\n'
    

    【讨论】:

    • 我仍然不确定你想用引号做什么,但我认为这就是你现在要做的......
    • 反斜杠更少:"""{ " \n }""".replaceAll("""(["{}\\n])""", "'$1'" )
    • @yakshaver - 您的示例分别替换 n\ ,例如"no" => "'n'o"。至于引号前面的反斜杠,这就是为什么我说我不确定他想用引号做什么。我认为他实际上可能正在寻找\" 而不仅仅是"
    • 你是对的。这个怎么样: "{ \" \n }".replaceAll("""(["{}\n])""", "'$1'")
    • @yakshaver - 现在它替换了一个实际的换行符而不是字符序列 反斜杠 n
    【解决方案3】:

    认为这是你的字符串:

    var actualString = "Hi {  {  { string in curly brace }  }   } now quoted string :  \" this \" now next line \\\n second line text"
    

    解决方案:

    var replacedString = Seq("\\{" -> "'{'", "\\}" -> "'}'", "\"" -> "'\"'", "\\\n" -> "'\\\n'").foldLeft(actualString) { _.replaceAll _ tupled (_) }
    
    scala> var actualString = "Hi {  {  { string in curly brace }  }   } now quoted string :  \" this \" now next line \\\n second line text"
    actualString: String =
    Hi {  {  { string in curly brace }  }   } now quoted string :  " this " now next line \
     second line text
    
    scala>      var replacedString = Seq("\\{" -> "'{'", "\\}" -> "'}'", "\"" -> "'\"'", "\\\n" -> "'\\\n'").foldLeft(actualString) { _.replaceAll _ tupled (_) }
    replacedString: String =
    Hi '{'  '{'  '{' string in curly brace '}'  '}'   '}' now quoted string :  '"' this '"' now next line \'
    ' second line text
    

    希望这会有所帮助:)

    【讨论】:

    • 对于这么老的问题,如果您指出您的答案提供了其他答案没有提供的内容,它会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2022-08-10
    • 2011-09-15
    相关资源
    最近更新 更多