最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Create array of regexp match(multiline, javascript) - Stack Overflow

programmeradmin0浏览0评论

I want to create array of javascript's regexp match string from the text below.

.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

and desired array is below

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"

In Java, I can do like ^\..*?(?=(^\.|\Z)), but in Javascript there is no \Z, . doesn't match newline character, and $ matches newline character (not just the end of string).

How can I achieve this array?
I use this site ( ) to test regexp.

I want to create array of javascript's regexp match string from the text below.

.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

and desired array is below

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"

In Java, I can do like ^\..*?(?=(^\.|\Z)), but in Javascript there is no \Z, . doesn't match newline character, and $ matches newline character (not just the end of string).

How can I achieve this array?
I use this site ( http://www.gethifi./tools/regex ) to test regexp.

Share Improve this question edited Jun 20, 2018 at 16:59 Cœur 38.8k25 gold badges206 silver badges278 bronze badges asked Nov 2, 2011 at 4:44 yshrsmzyshrsmz 1,1792 gold badges15 silver badges34 bronze badges 1
  • By the way, $ will only match the end of string unless you add the m flag. For example, /foo$/m would match "foo" in "foo\nbar" but /foo$/ would not. – davidchambers Commented Nov 2, 2011 at 5:52
Add a ment  | 

2 Answers 2

Reset to default 6

text.split(/\r?\n^(?=\.)/gm) produces the same array.

text.match(/^\..*(\r?\n[^.].*)*/gm) ugly, but still.

Here it is in a single regular expression:

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)

outputs:

[
  ".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"
]

Some useful tricks:

  • use [\s\S] to match any character
  • use (?![\s\S]) to simulate \Z
发布评论

评论列表(0)

  1. 暂无评论