When I use javascript write regex.
var regex = new RegExp("^[ ]{"+p1.length+"}\* ([^\n]*)", "gm")
btw, i have alert(p1.length)
it's value 0
.
i got error:
SyntaxError: Invalid regular expression: nothing to repeat
why?
this is same error
var regex = new RegExp("^ {"+p1.length+"}\* ([^\n]*)", "gm")
but this is right:
var r="^ {"+p1.length+"}[0-9]+\. ([^\n]*)"
var regex = new RegExp(r, "gm")
my question is why???
var regex = new RegExp("^ {"+p1.length+"}[*] ([^\n]*)", "gm") //this is ok
var regex = new RegExp("^ {"+p1.length+"}\\* ([^\n]*)", "gm") //and this is ok too.
so when we use string build a regex, we need double\\ it is so trick.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
{n} Matches exactly n occurrences of the preceding expression. N must be a positive integer. For example, /a{2}/ doesn't match the 'a' in "candy," but it does match all of the a's in "caandy," and the first two a's in "caaandy."
so my use {0} is right, no problem. the problem is we need \\ in string to build regex, just like @Andreas say, thanks.
First things first, you didn't escape your regexes. You should probably do that...
Your 2 erroneous regexes have 2 separate errors.
Your first one is trying to quantify [ ]{0}
with "0 or more times".
[ ]{0}
repeated 100 or 1000 or however many times is still an empty string. This means that the regex will never stop matching if this were valid, because it would not have proceeded to match any more characters after [ ]{0}*
.
Your second regex is trying to repeat ^
0 times.
^
is not a character, it is just a zero-width position - the start of the string. The same goes with other "positions" like \b
. There can't be 2 "starts" of a string next to each other.
I will now explain why the two regexes in your edit works.
[*]
is a character class. In a character class, *
loses its meaning of "zero or more times" and becomes literal. So you are just matching the character *
after no spaces.
\\*
unescaped is just \*
. Here the *
loses its meaning again since it is after a backslash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With