简体   繁体   English

使用状态模式进行字符串解析

[英]Using State Pattern for String parsing

A part of my programming assignment needs parsing a String using the State Pattern.我的编程作业的一部分需要使用状态模式解析字符串。 It is explicitly requested that the State Pattern is used, so no other option is allowed.明确要求使用状态模式,因此不允许使用其他选项。

An example String is: " update user filter userId=user3 set name=xxx ".一个示例字符串是:“更新用户过滤器userId=user3 set name=xxx ”。 (The bold ones are keywords). (粗体是关键字)。

The request is like follows:请求如下:

While parsing the query you should use State Pattern.在解析查询时,您应该使用状态模式。 There are four states: OPERATOR, OBJECT, FILTER and VALUES.有四种状态:操作者、对象、过滤器和值。

I looked examples about State Pattern, I think I got it, but I couldn't be able to figure out how to apply it to string parsing.我看了关于状态模式的例子,我想我明白了,但我无法弄清楚如何将它应用于字符串解析。

I'll be glad if someone gives me some hints.如果有人给我一些提示,我会很高兴。

First create your state interface.首先创建您的状态接口。 Perhaps with one method: parse也许用一种方法: parse

Create your 4 concrete states.创建您的 4 个具体状态。 Implement each to parse only its part of the string, Your context will be in responsibility to split the string and change states.实现每个以仅解析字符串的一部分,您的上下文将负责拆分字符串并更改状态。

In Your context class you do the following:在您的上下文类中,您执行以下操作:

  • You know that the OperatorState is always the first one, so init你知道OperatorState总是第一个,所以 init
  • you context's state to it.你上下文的状态。 Read the string until you reach the next读取字符串直到到达下一个
  • keyword ("filter") Move that string you've read to the current state (Opearator)关键字(“过滤器”)将您读取的字符串移动到当前状态(运算符)
  • Change the current state to the next one ( FilterState )将当前状态更改为下一个( FilterState

And so on...等等...

If you understand the state pattern then this should be enough to build a solution.如果您了解状态模式,那么这应该足以构建解决方案。

Note: You can have a dictionary with keywords and states so you can automate it, but in your case i think a simple solution is enough.注意:你可以有一个带有关键字和状态的字典,这样你就可以自动化它,但在你的情况下,我认为一个简单的解决方案就足够了。

Good Luck祝你好运

I might be misunderstanding what you mean by state pattern, so if i get this wrong then ignore me,我可能误解了您所说的状态模式,所以如果我弄错了,请忽略我,

let's say you're looking for the string "abac"假设您正在寻找字符串"abac"

you start with the empty state "" and iterate down the characters of the string.您从空状态""并向下迭代字符串的字符。 if you get an 'a' you go to state "a" get a 'b' , go to state "ab" , get 'a' , you go back to state "a" , anything else to the empty state, etc如果你得到一个'a'你去状态"a"得到一个'b' , 去状态"ab" , 得到'a' , 你回到状态"a" , 任何其他状态到空状态, 等等

once you get to state "abac" you've found your string.一旦你说出"abac"你就找到了你的字符串。 It's a simple DFA to find a regular expression.查找正则表达式是一个简单的 DFA。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM