2

我遇到了解析器解析器的不清楚的行为,所以我想解析字符串一样

>  <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"
4

2 回答 2

3

在您的示例中,parseProperties解析器被执行多次,直到 eof遇到。问题是parseProperties在您的示例中不使用尾随空格,因此在解析最后一个标签后,剩余的字符串是"\n\n",这不会触发您的终止条件,因为它不是输入的结尾。这会导致parseProperties 再次尝试,这会消耗空格,但在尝试吃'>'.

尝试将您的修改parseTest为以下

test = "\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 (skipMany newline >> eof)) test

这会在检查它是否在输入末尾之前尝试去除前面的空格。

于 2013-07-25T14:46:47.797 回答
2

如果“\n”的数量是随机的,我会使用这个版本(而不是添加一个额外的解析器):

parseProperties :: Parser (String,String)
parseProperties = do
  skipMany newline -- optional newline(s)
  char '>' >> spaces >> char '<'
  propName <- many1 (noneOf ">")
  char '>'
  newline
  propValue <- many1 (noneOf "\n")
  skipMany newline  -- optional newline(s)
  return (propName,propValue)

我试过这个版本:

 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" 

并得到:

[("CdId","1"),("Mol Weight","270.2369"),("Formula","C15H10O5"),("LOG_ER_RBA","-0.36"),     ("ACTIVITY","1")]
于 2013-07-25T15:03:31.093 回答