检索对象方法

时间:2016-06-06 09:52:37

标签: scala

我在{myObjectIdIKnow?someInfo,{someBracedInfo},{someOtherBracedInfo},someInfo,...,lastInfo} someInfo内有一个“对象”,其中包含以下拼写错误。

我想检索其内容(即从lastInfodef retrieveMyObject(line: String, myObjectId: String) = { if (line.contains(myObjectId)) { var openingDelimiterCount = 0 var closingDelimiterCount = 0 val bit = iLine.split(myObjectIdIKnow).last var i = -1 do { i += 1 if (bit(i).equals("{")) openingDelimiterCount += 1 else if (bit(i).equals("}")) closingDelimiterCount += 1 } while (lDelimiterOpeningCount >= closingDelimiterCount) if (i.equals(0)) bit else bit.splitAt(i)._1 } } )。

以下,我建立的功能:

myObjectId

我与我的{匹配并浏览输入行的每个字符以检查它是否是大括号分隔符,然后比较}<input type="checkbox" name="stOne" id="stOne" value="1"/> <select class="input" name="selectOne" id="selectOne"> <?php $check_sql = mysql_query("SELECT * FROM DBtable"); while ($check_row = mysql_fetch_assoc($check_sql)) { $id = $check_row['id']; $st = $check_row['style']; echo "<option value='" . $st . "'>" . $st . "</option>"; } ?> </select> 的数量:if第二个比第一个更大,这意味着我到达了我的内容的末尾,因此我检索它。

它似乎不是一个好方法,我想知道我能做什么更好的方法呢?

1 个答案:

答案 0 :(得分:1)

我尝试使用Scala Parser Combinators实现简单的解析器。这就是我得到的。我对解析器组合器不是很有经验,但为了好奇而做了一些工作。

import scala.util.parsing.combinator.JavaTokenParsers

case class InfoObject(id: String, objInfo: String, bracedInfos: List[String], infos: List[String])

class ObjectParser extends JavaTokenParsers {

  def objDefinition: Parser[InfoObject] = "{" ~> (idPlusInfo <~ ",") ~ (bracedInfos <~ ",") ~ infos <~ "}" ^^ {
    case (id, objInfo) ~ bracedInfos ~ infos => InfoObject(id, objInfo, bracedInfos, infos)
  }

  def idPlusInfo: Parser[(String, String)] = (infoObj <~ "?") ~ infoObj ^^ { case id ~ info => (id, info) }

  def bracedInfos: Parser[List[String]] = repsep(bracedInfo, ",")

  def bracedInfo: Parser[String] = "{" ~> infoObj <~ "}"

  def infos: Parser[List[String]] = repsep(infoObj, ",")

  def infoObj: Parser[String] = """\w+""".r
}

val parser = new ObjectParser()

parser.parse(parser.infoObj, "someInfo").get == "someInfo"  // true

parser.parse(parser.bracedInfo, "{someBracedInfo}").get == "someBracedInfo" // true

val expected = InfoObject(
  "myObjectIdIKnow",
  "someInfo",
  List("someBracedInfo", "someOtherBracedInfo"),
  List("someInfo", "lastInfo")
)

val objectDef = "{myObjectIdIKnow?someInfo,{someBracedInfo},{someOtherBracedInfo},someInfo,lastInfo}"

parser.parse(parser.objDefinition, objectDef).get == expected  // true