创建正则表达式匹配数组(多行,javascript)

时间:2011-11-02 04:44:27

标签: javascript regex

我想从下面的文本中创建javascript的regexp匹配字符串数组。

.root
 this is root
..child 1
 this is child 1
 this is also child 1's content.
...child 1-1
 this is child 1-1

..child 2
 this is child 2
...child 2-1
 this is child 2-1
.root 2
 this is root 2

,所需的数组在

之下
array[0] = ".root
 this is root"

array[1] = "..child 1
 this is child 1
 this is also child 1's content"

array[2] = "...child 1-1
 this is child 1-1
"

array[3] = "..child 2
 this is child 2"

array[4] = "...child 2-1
 this is child 2-1"

array[5] = ".root 2
 this is root 2"

在Java中,我可以像^\..*?(?=(^\.|\Z))那样,但在Javascript中没有\Z.与换行符不匹配,$匹配换行符(不只是字符串的结尾。)

如何实现此阵列?
 我使用这个站点(http://www.gethifi.com/tools/regex)来测试regexp。

2 个答案:

答案 0 :(得分:6)

text.split(/\r?\n^(?=\.)/gm)生成相同的数组。

text.match(/^\..*(\r?\n[^.].*)*/gm)丑陋,但仍然。

答案 1 :(得分:3)

这是一个正则表达式:

var re = /^[.][\s\S]*?(?:(?=\r?\n[.])|(?![\s\S]))/gm
var match
var matches = []
while (match = re.exec(text)) {
  matches.push(match[0])
}
console.log(matches)

输出:

[
  ".root\nthis is root",
  "..child 1\n this is child 1\n this is also child 1's content.",
  "...child 1-1\n this is child 1-1\n",
  "..child 2\n this is child 2",
  "...child 2-1\n this is child 2-1",
  ".root 2\n this is root 2"
]

一些有用的技巧: