gpt4 book ai didi

regex - 如何在Scala中拆分字符串但保持与正则表达式匹配的部分?

转载 作者:行者123 更新时间:2023-12-04 14:59:24 24 4
gpt4 key购买 nike

我的问题和 Split string including regular expression match 一样但对于 Scala。不幸的是,JavaScript 解决方案在 Scala 中不起作用。

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

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

我想得到以下序列: "hello world" :: "<1>" :: "this is some random text" :: "<3>" :: "foo" :: "<12>" .

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

最佳答案

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

关于regex - 如何在Scala中拆分字符串但保持与正则表达式匹配的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19966831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com