正则表达式,用于捕获方括号之间的开始和结束空格(Regular expression to catch start and end whitespaces between square bracket

编程入门 行业动态 更新时间:2024-10-24 08:25:34
正则表达式,用于捕获方括号之间的开始和结束空格(Regular expression to catch start and end whitespaces between square brackets)

我需要一个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));
} 
  
 

更多推荐

本文发布于:2023-08-07 04:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方括号   空格   结束   正则表达式   Regular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!