我需要一个javascript中的正则表达式,在string类似的情况下会失败:
foo[ bar] foo[bar ] foo[ bar ]foo可以是任何单词(也可以包含特殊字符作为-和. ),同样适用于bar 。
如果string只是:它应该不会失败:
[ bar] [bar ] [ bar ]如果string是,则不应该失败:
foo[bar]一点背景信息。 我正在编写一个自定义的linter规则,如果引用的数组在括号中有不需要的空格,它将失败。 任何帮助是极大的赞赏。
这是我到目前为止( Regex101 ):
\[([^\]]+)\]但是这会考虑到整个括号并且不会评估开头(它应该先于)。 此外,它应该只评估空格的存在。
I need a regular expression in javascript which will fail in cases when string is something like:
foo[ bar] foo[bar ] foo[ bar ]foo can be any word (also can contain special characters as - and .), same goes for bar.
It should not fail if string is just:
[ bar] [bar ] [ bar ]And should not fail if string is:
foo[bar]A bit of background info. I am writing a custom linter rule which will fail if the referenced array has unneeded spaces in brackets. Any help is greatly appreciated.
This is what I have so far (Regex101):
\[([^\]]+)\]But this catches the whole bracket into account and does not evaluate the beginning (it should be preceeded). Also, it should evaluate the presence of whitespaces only.
最满意答案
看来你只想匹配1)之前有一个或多个单词字符的字符串(和2)在[或之前]之前有空格。
你可以用
/\w+\[(\s[^\]]*|[^\]]*\s)]/请参阅正则表达式演示 。
细节
\w+ - 1个或更多单词字符 \[ - 一个[ (\s[^\]]*|[^\]]*\s) - 两种选择中的任何一种: \s[^\]]* - 一个空格字符后面跟着0 +字符除了] | - 要么 [^\]]*\s - 除了以外的0+字符后跟一个空白字符 ] - a ] char。JS演示:
var rx = /\w+\[(\s[^\]]*|[^\]]*\s)]/; var strs = [ "foo[ bar]", "foo[bar ]", "foo[ bar ]", "[ bar]", "[bar ]", "[ bar ]"]; for (var s of strs) { console.log(s, "=>", rx.test(s)); }It seems you only want to match strings that 1) have 1 or more word chars before ( and 2) have whitespace right after [ or right before ].
You may use
/\w+\[(\s[^\]]*|[^\]]*\s)]/See the regex demo.
Details
\w+ - 1 or more word chars \[ - a [ (\s[^\]]*|[^\]]*\s) - either of the two alternatives: \s[^\]]* - a whitespace char followed with 0+ chars other than ] | - or [^\]]*\s - 0+ chars other than ] followed with a whitespace char ] - a ] char.JS demo:
var rx = /\w+\[(\s[^\]]*|[^\]]*\s)]/; var strs = [ "foo[ bar]", "foo[bar ]", "foo[ bar ]", "[ bar]", "[bar ]", "[ bar ]"]; for (var s of strs) { console.log(s, "=>", rx.test(s)); }
更多推荐
发布评论