使用Javascript进行字符串操作

时间:2015-12-15 20:02:44

标签: javascript string

我有这个字符串:

Table {is {red|blue|orange|white|green-{yellow|black}} |has {{twenty|thirty}two|{{two hundered and |three hundered and }fourty |fifty }three|four} legs} and is placed { in corner | in the middle } of office and {printer|phone} is {{gray-|}black|white}.

我想要一些我可以使用它的数据结构,你能提出一些建议吗?

这是我的尝试:

var matches = $scope.fileContent.match(/{([^}]+)}/g);

for (var i = 0; i < matches.length; i++) {
   console.log(matches[i]);
}

我想要随机句子

可能的结果:

 - Table is blue and is placed in corner of office and printer is black.
 - Table has three hundered and fourty three legs and is placed in the middle of office and phone is gray-black.

1 个答案:

答案 0 :(得分:2)

这种句子结构的语法是:

SENTENCE     := PARTIAL optional SENTENCE
PARTIAL      := TEXT or BRANCH
BRANCH       := '{' SENTENCE ALTERNATIVES '}'
ALTERNATIVES := '|' SENTENCE optional ALTERNATIVES

也许我可以在不同的阶段使用更清晰的名字,但你明白了。您的任何句子都可以使用此语法的规则进行细分。解析后,您将以树形结构获得句子。

将字符串解析为此树结构后,您可以遍历它,并随机选择您所采用的分支。 JavaScript中的一个示例:

var string = "A table {is {red|blue|green}|has {four|five} legs}"
var index = 0
var root = new Node()
var current = root

function Node() {
    this.text = ""
    this.options = []
    this.next = null
}

Node.prototype.toString = function(){
    var string = this.text;
    if (this.options.length > 0) {
        var rnd = Math.floor(Math.random() * this.options.length)
        string += this.options[rnd].toString()
    }
    if (this.next != null)
        string += this.next.toString()
    return string
}

function parse() {
    text()
    if (index == string.length)
        return

    if (string[index] == "{") {
        index++
        options()
        var next = new Node()
        current.next = next
        current = next
        parse()
    }
}

function options() {
    var parent = current
    while(true) {
        current = new Node()
        parent.options.push(current)
        parse()
        index++
        if (string[index - 1] != '|')
            break
    }
    current = new Node()
    parent.next = current
}

function text() {
    while (index < string.length && "{|}".indexOf(string[index]) == -1) {
        current.text += string[index]
        index++
    }
}

parse()
alert(root.toString())

只是抬头 - 这不会处理这些字符串:

  • &#34;一些文字{没有结束大括号&#34;
  • &#34;意想不到的|管道符号&#34;
  • &#34;一个意想不到的结束大括号&#34;

我允许你自己添加。