Scala regex:如何从字符串中提取年份?

时间:2022-02-22 18:52:10

Trying to extract years from String, but this doesn't seem to work:

试图从弦中提取年数,但这似乎行不通:

val p = "(19|20)\\d\\d".r
val str = "At the time of its release, Twilight Princess was considered the greatest entry in the Zelda series by many critics, including writers for 1UP.com, Computer and Video Games, Electronic Gaming Monthly, Game Informer, GamesRadar, IGN, and The Washington Post. It received several Game of the Year awards, and was the most critically acclaimed game of 2006. In 2011, the Wii version was rereleased under the Nintendo Selects label. A high-definition port for the Wii U, The Legend of Zelda: Twilight Princess HD, will be released in March 2016."
println(p.findAllIn(str).toSeq)

it gives me:

它给我:

Seq[String] = Stream(2006, ?)

missing a "2016" and "2011" plus an extra "?". Any ideas where I'm going wrong?

错过了一个“2016”和“2011”再加上一个“?”你知道我哪里出错了吗?

1 个解决方案

#1


3  

The code works well, the reason why you are not seeing all the matches is becase findAll returns an iterator, if you convert it to a Seq it will pick the Stream collection that is a lazy collection (it will perform the matching as you requests elements)

代码工作得很好,您没有看到所有匹配的原因是由于findAll返回一个迭代器,如果您将它转换为Seq,它将选择一个延迟收集的流集合(它将执行与您请求元素的匹配)

To see all the results do this

要看到所有的结果都是这样的。

println(p.findAllIn(str).toList)

This will convert the iterator to a List (this operation will extract all matching years).

这将把迭代器转换为列表(此操作将提取所有匹配年份)。

The meaning of that ? is that the next element of the stream has not been computed yet

这是什么意思?流的下一个元素还没有被计算出来吗

#1


3  

The code works well, the reason why you are not seeing all the matches is becase findAll returns an iterator, if you convert it to a Seq it will pick the Stream collection that is a lazy collection (it will perform the matching as you requests elements)

代码工作得很好,您没有看到所有匹配的原因是由于findAll返回一个迭代器,如果您将它转换为Seq,它将选择一个延迟收集的流集合(它将执行与您请求元素的匹配)

To see all the results do this

要看到所有的结果都是这样的。

println(p.findAllIn(str).toList)

This will convert the iterator to a List (this operation will extract all matching years).

这将把迭代器转换为列表(此操作将提取所有匹配年份)。

The meaning of that ? is that the next element of the stream has not been computed yet

这是什么意思?流的下一个元素还没有被计算出来吗