6

My question is the same as Split string including regular expression match but for Scala. Unfortunately, the JavaScript solution doesn't work in Scala.

I am parsing some text. Let's say I have some string:

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

I would like to get the following Seq: "hello world" :: "<1>" :: "this is some random text" :: "<3>" :: "foo" :: "<12>".

Note that I am spliting the string whenever I encounter a <"number"> sequence.

4

2 回答 2

6
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+是行不通的。看到这个问题

s.split("""((?=<\d+>)|(?<=<\d+>))""")
java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 19
于 2013-11-14T00:31:35.950 回答
1

Here's a quick, but a little hacky solution:

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>)

Of course, the problem with this solution is that I gave the underscore character a special meaning. If it occurs naturally in the original string, you'll get bad results. So you have to either choose another magic character sequence for which you are sure that it won't occur in the original string or play with some more escaping/unescaping.

Another solution involves usage of lookahead and lookbehind patterns, as described in this question.

于 2013-11-14T00:15:42.587 回答