【问题标题】:How to split String in Scala but keep the part matching the regular expression?如何在Scala中拆分字符串但保持与正则表达式匹配的部分?
【发布时间】:2013-11-13 23:50:19
【问题描述】:

我的问题与Split string including regular expression match 相同,但针对的是 Scala。不幸的是,JavaScript 解决方案在 Scala 中不起作用。

我正在解析一些文本。假设我有一些字符串:

"hello wold <1> this is some random text <3> foo <12>"

我想获得以下 Seq:"hello world" :: "&lt;1&gt;" :: "this is some random text" :: "&lt;3&gt;" :: "foo" :: "&lt;12&gt;"

请注意,每当遇到 序列时,我都会拆分字符串。

【问题讨论】:

    标签: regex scala


    【解决方案1】:
    val s = "hello wold <1> this is some random text <3> foo <12>"
    s: java.lang.String = hello wold <1> this is some random text <3> foo <12>
    
    s.split("""((?=<\d{1,3}>)|(?<=<\d{1,3}>))""")
    res0: Array[java.lang.String] = Array(hello wold , <1>,  this is some random text , <3>,  foo , <12>)
    

    您是否真的尝试过您的编辑?拥有\d+ 不起作用。见this question

    s.split("""((?=<\d+>)|(?<=<\d+>))""")
    java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 19
    

    【讨论】:

    • 您能解释一下?=?&lt;= 正在做什么或指向一个页面吗?
    • 当然,它们被称为环视,是正则表达式的一部分。你可以在这里阅读更多关于它们的信息:rexegg.com/regex-lookarounds.html
    • 没问题,我们是来学习的。我遇到了同样的问题,也不得不研究这个问题。 ;) 您可以使用这些在线工具快速试用 Scala 代码块:simplyscala.comcompileonline.com/compile_scala_online.php
    • 没看懂,上面代码哪部分导致分隔符不消失?是正则表达式匹配前瞻和后瞻的事实吗?
    【解决方案2】:

    这是一个快速但有点老套的解决方案:

    scala> val str = "hello wold <1> this is some random text <3> foo <12>"
    str: String = hello wold <1> this is some random text <3> foo <12>
    
    scala> str.replaceAll("<\\d+>", "_$0_").split("_")
    res0: Array[String] = Array("hello wold ", <1>, " this is some random text ", <3>, " foo ", <12>)
    

    当然,这个解决方案的问题是我给下划线字符赋予了特殊的含义。如果它自然地出现在原始字符串中,你会得到不好的结果。因此,您必须选择另一个您确信它不会出现在原始字符串中的魔术字符序列,或者使用更多的转义/取消转义。

    另一种解决方案涉及使用前瞻和后瞻模式,如this question 中所述。

    【讨论】:

      猜你喜欢
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2015-03-15
      相关资源
      最近更新 更多