Checking index like pattern with Regular Expression
I try to check a index string (e.g. $string = "[index]"
) with a regular expression. This index must be checked against the illegal characters [
and ]
inside the index name. So for example [in[dex]
must fail.
My first try:
/^\[[^\[\]]*\]$/
So the the string must start and end with [
and ]
. With a negated character class I now try to make inline square brackets illegal but this doesn't work propably.
Any ideas?
Thanks in advanced,
JohnnyEdit: I'm very confused. I rerun the tests I wrote for this and it works fine now. Think I have missed something when working in the history of my editor. Thanks for h开发者_StackOverflowelp to everyone.
This /^\[[^[\]]+\]$/
worked for me.
/^\[[^[\]]+\]$/.test("[index]") // true
/^\[[^[\]]+\]$/.test("[in[dex]") // false
/^\[[^[\]]+\]$/.test("[in]dex]") // false
/^\[
begins with a bracket[^
open "not" syntax[\]
exclusion characters]+
close not and say we only want 1+ things which pass the not syntax (change to asterisk to match [])\]$/
Expression will end with the closing bracket.
/^\[[^][]+\]$/
Is that what you're looking for?
- Match a [ character
- Match a single character NOT present in the list "][" Between 1 and unlimited times, as many times as possible, giving back as needed (greedy)
- Match a ] character
The only reason I can see right now that your correct regex wouldn't work is if you didn't escape it properly when quoting in PHP. It should be quoted something like: "/^\\[[^[\\]]*\\]$/"
.
What you have should work using preg_match. If you are using ereg, then it will not work. Ereg has been deprecated as of PHP 5.3. I tried your regex out at regextester.com against the following, and it worked under preg and failed under ereg.
[index]
[in[dex]
[in[de]x]
d[index]
[inde]x]
[index]d
精彩评论