Ignoring an arbitrary prefix in a parser combinator

≡放荡痞女 提交于 2019-12-24 11:15:59

问题


After getting fed up with regexes I have been trying to use scala's parser combinator libraries as a more intuitive replacement for regexes. However, I've run into a problem when I want to search a string for a pattern and ignore things that come before it, for example if I want to check if a string contains the word "octopus" I can do something like

val r = "octopus".r
r.findFirstIn("www.octopus.com")

Which correctly gives Some(octopus).

However, using parser combinators

import scala.util.parsing.combinator._
object OctopusParser extends RegexParsers {

  def any = regex(".".r)*
  def str = any ~> "octopus" <~ any

  def parse(s: String) = parseAll(str, s) 
}

OctopusParser.parse("www.octopus.com")

However I get an error on this

scala> OctopusParser.parse("www.octopus.com")
res0: OctopusParser.ParseResult[String] = 
[1.16] failure: `octopus' expected but end of source found

www.octopus.com

Is there a good way to accomplish this? From playing around, it seems that any is swallowing too much of the input.


回答1:


The problem is that your 'any' parser is greedy, so it is matching the whole line, leaving nothing for 'str' to parse.

You might want to try something like:

object OctopusParser extends RegexParsers {

  def prefix = regex("""[^\.]*\.""".r) // Match on anything other than a dot and then a dot - but only the once
  def postfix = regex("""\..*""".r)* // Grab any number of remaining ".xxx" blocks
  def str = prefix ~> "octopus" <~ postfix

  def parse(s: String) = parseAll(str, s)
}

which then gives me:

scala> OctopusParser.parse("www.octopus.com")
res0: OctopusParser.ParseResult[String] = [1.13] parsed: octopus

You may need to play around with 'prefix' to match the range of input you are expecting, and might want to use the '?' lazy marker if it is being too greedy.



来源:https://stackoverflow.com/questions/17559909/ignoring-an-arbitrary-prefix-in-a-parser-combinator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!