在Haskell中匹配regex模式

时间:2021-12-14 22:35:21

In Scala, I have a regular expression pattern match like this:

在Scala中,我有一个正则表达式模式匹配如下:

val Regex = """(\d{4})/(\d{2})/(\d{2})""".r
val Regex(year, month, day) = "2013/01/06"

The result is:

其结果是:

year: String = 2013
month: String = 01
day: String = 06

How can I accomplish a similar result in Haskell? In other words, can I match a regular expression containing groups and assign the groups to identifiers?

我怎样才能在Haskell中实现类似的结果呢?换句话说,我可以匹配包含组的正则表达式并将组赋给标识符吗?

2 个解决方案

#1


15  

This works for me:

这工作对我来说:

Prelude Text.Regex.Posix> "2013/01/06" =~ "([0-9]+)/([0-9]*)/([0-9]*)" :: (String,String,String,[String])
("","2013/01/06","",["2013","01","06"])

(ghci 7.4.2 on OS X)

(关于OS X的ghci 7.4.2)

#2


10  

Expanding on Chris's answer, the following works and is similar to my Scala version:

扩展克里斯的答案,下面的作品和我的Scala版本类似:

ghci> :m +Text.Regex.Posix
ghci> let (_, _, _, [year, month, day]) ="2013/01/06" =~ "([0-9]+)/([0-9]*)/([0-9]*)" :: (String,String,String,[String])
ghci> year
"2013"
ghci> month
"01"
ghci> day
"06"

#1


15  

This works for me:

这工作对我来说:

Prelude Text.Regex.Posix> "2013/01/06" =~ "([0-9]+)/([0-9]*)/([0-9]*)" :: (String,String,String,[String])
("","2013/01/06","",["2013","01","06"])

(ghci 7.4.2 on OS X)

(关于OS X的ghci 7.4.2)

#2


10  

Expanding on Chris's answer, the following works and is similar to my Scala version:

扩展克里斯的答案,下面的作品和我的Scala版本类似:

ghci> :m +Text.Regex.Posix
ghci> let (_, _, _, [year, month, day]) ="2013/01/06" =~ "([0-9]+)/([0-9]*)/([0-9]*)" :: (String,String,String,[String])
ghci> year
"2013"
ghci> month
"01"
ghci> day
"06"