代码链接

demo如下,定义好rule后进行parse。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const rule = AndRule.of(
  [
    TextRule.of("hello", "HELLO_RULE"),
    OrRule.of(
      [TextRule.of(", "), TimesRule.of(3, TextRule.of(" ", "SPACE"), "TIMES")],
      "NO_NAME"
    ),
    TextRule.of("world", "WORLD"),
    OneOrMoreRule.of(TextRule.of("!"), "SAMPLE")
  ],
  "HELLO_WORLD"
);

console.log(JSON.stringify(rule.accept("hello   world!!!")));

结果为:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{
  "contain": true,
  "group": {
    "groups": [
      { "text": "hello", "name": "HELLO_RULE" },
      {
        "groups": [
          {
            "groups": [
              { "text": " ", "name": "SPACE" },
              { "text": " ", "name": "SPACE" },
              { "text": " ", "name": "SPACE" }
            ],
            "name": "TIMES"
          }
        ],
        "name": "NO_NAME"
      },
      { "text": "world", "name": "WORLD" },
      {
        "groups": [
          { "text": "!", "name": null },
          { "text": "!", "name": null },
          { "text": "!", "name": null }
        ],
        "name": "SAMPLE"
      }
    ],
    "name": "HELLO_WORLD"
  }
}
  

当然,这离真正可用还有很远:

红红姐的教导