我遇到了解析器解析器的不清楚的行为,所以我想解析字符串一样
> <CdId>
1
> <Mol Weight>
270.2369
> <Formula>
C15H10O5
> <LOG_ER_RBA>
-0.36
> <ACTIVITY>
1
我写了一个解析器
parseProperties = do
skipMany1 newline
char '>' >> spaces >> char '<'
propName <- many1 (noneOf ">")
char '>'
newline
propValue <- many1 (noneOf "\n")
return (propName,propValue)
这个解析器很好地解析了一个项目,并且还能够解析几个:
parseTest (count 5 parseProperties) "\n> <CdId>\n1\n\n> <Mol Weight>\n270.2369\n\n> <Formula>\nC15H10O5\n\n> <LOG_ER_RBA>\n-0.36\n\n> <ACTIVITY>\n1\n\n"
结果
[("CdId","1"),("Mol Weight","270.2369"),("Formula","C15H10O5"),("LOG_ER_RBA","-0.36"),("ACTIVITY","1")]
尽管如此,我还是没有找到解析随机数属性的方法。如果我尝试
parseTest (many1 parseProperties) "\n> <CdId>\n1\n\n> <Mol Weight>\n270.2369\n\n> <Formula>\nC15H10O5\n\n> <LOG_ER_RBA>\n-0.36\n\n> <ACTIVITY>\n1\n\n"
或者
parseTest (manyTill parseProperties (try eof)) "\n> <CdId>\n1\n\n> <Mol Weight>\n270.2369\n\n> <Formula>\nC15H10O5\n\n> <LOG_ER_RBA>\n-0.36\n\n> <ACTIVITY>\n1\n\n"
解析器失败
parse error at (line 17, column 1):
unexpected end of input
expecting new-line or ">"
但是,如果我使用 anyChar 解析器,它不会失败。
parseTest (manyTill anyChar (try eof)) "\n> <CdId>\n1\n\n> <Mol Weight>\n270.2369\n\n> <Formula>\nC15H10O5\n\n> <LOG_ER_RBA>\n-0.36\n\n> <ACTIVITY>\n1\n\n"
"\n> <CdId>\n1\n\n> <Mol Weight>\n270.2369\n\n> <Formula>\nC15H10O5\n\n> <LOG_ER_RBA>\n-0.36\n\n> <ACTIVITY>\n1\n\n"