用于匹配括号内容的正则表达式

时间:2017-07-19 04:57:59

标签: javascript regex

我需要一个RegEx,选择类似[something的内容而不支持[something],我知道这个

/\[[\w]+/g

但是,如果不选择[]之间的内容,我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

正则表达式无法解决您的问题。

如果您始终匹配整个字符串,则可以确保字符串的结尾出现在"]"字符:



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.'));
});