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.
-
By the way,
$
will only match the end of string unless you add them
flag. For example,/foo$/m
would match "foo" in "foo\nbar" but/foo$/
would not. – davidchambers Commented Nov 2, 2011 at 5:52
2 Answers
Reset to default 6text.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