作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试读取脚本文件,然后处理并将其输出到 html 文件。在我的脚本文件中,只要有 @title(这是一个标题),我就会在我的 html 中添加标签 [header] 这是一个标题 [/header]输出。所以我的做法是先读取脚本文件,将内容写入字符串,处理字符串,然后将字符串写入html文件。
为了识别@title,我需要逐个字符地读取字符串中的字符。当我读取“@”时,我需要检测下一个字符以查看它们是否是标题。
问题:如何在 Haskell 中遍历字符串(这是一个字符列表)?
最佳答案
例如,您可以使用简单的递归技巧
findTag [] = -- end of list code.
findTag ('@':xs)
| take 5 xs == "title" = -- your code for @title
| otherwise = findTag xs
findTag (_:xs) = findTag xs
所以基本上,如果下一个字符(列表头)是“@”,则只需进行模式匹配,然后检查接下来的 5 个字符是否形成“标题”。如果是这样,您可以继续解析代码。如果下一个字符不是“@”,您只需继续递归。一旦列表为空,您就会到达第一个模式匹配。
其他人可能有更好的解决方案。
我希望这能回答您的问题。
编辑:
为了获得更大的灵 active ,如果您想查找特定标签,可以这样做:
findTag [] _ = -- end of list code.
findTag ('@':xs) tagName
| take (length tagName) xs == tagName = -- your code for @title
| otherwise = findTag xs
findTag (_:xs) _ = findTag xs
如果你这样做的话就这样
findTag text "title"
您将专门查找标题,并且可以随时将标记名更改为您想要的任何内容。
另一个编辑:
findTag [] _ = -- end of list code.
findTag ('@':xs) tagName
| take tLength xs == tagName = getTagContents tLength xs
| otherwise = findTag xs
where tLength = length tagName
findTag (_:xs) _ = findTag xs
getTagContents :: Int -> String -> String
getTagContents len = takeWhile (/=')') . drop (len + 1)
说实话,事情变得有点困惑,但实际情况是这样的:
首先删除 tagName 的长度,然后再删除左括号的长度,最后使用 takeWhile 获取字符直到右括号为止。
关于parsing - Haskell:遍历字符串/文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913399/
我是一名优秀的程序员,十分优秀!