I need a RegEx that select something like [something
and not support [something]
for first one I know this
/\[[\w]+/g
But for not selecting if content between []
I don't know what should I do.
I need a RegEx that select something like [something
and not support [something]
for first one I know this
/\[[\w]+/g
But for not selecting if content between []
I don't know what should I do.
Regex can't necessarily solve your problem.
If you're always matching the entire string, you can ensure that the end of the string comes before any occurrence of the "]" character:
var reg = /\[[^\]]+$/;
/*
How is this regex working?
- The first two characters, `"\["`, mean to match a literal "["
- The next 5 characters, `"[^\]]"`, match ANY character except
the "]" character. The outer "[]" define a character class,
and when "^" appears as the first character of a character
class it means to invert the character class, so only accept
characters which DON'T match. Then the only character which
cannot be matched is an escaped right-square-bracket: "\]"
- Add one more character to the previous 5 - `"[^\]]+"` - and
you will match any number (one or more) of characters which
aren't the right-square-bracket.
- Finally, match the `"$"` character, which means "end of input".
This means that no "]" character can be matched before the input
ends.
*/
[
'[',
'[aaa',
'aa[bb',
'[[[[',
']]]]',
'[aaa]',
'[aaa[]',
'][aaa'
].forEach(function(val) {
console.log('Match "' + val + '"? ' + (reg.test(val) ? 'Yes.' : 'No.'));
});