[英]regex Match string inside brackets which includes (or not includes) spaces
How do you capture a string with regex, that is a) inside round brackets, including the brackets, and b) includes a space (or alternatively doesn't include a space) inside the brackets, so to capture (test test), ( test), (test )
but not (test)
.您如何使用正则表达式捕获字符串,即a)在圆括号内,包括括号,并且b)在括号内包含空格(或者不包含空格),因此要捕获
(test test), ( test), (test )
但不是(test)
。
I've found a similar problem here that uses the expression我在这里发现了一个类似的问题,它使用了表达式
\((?!\s)[^()]+(?<!\s)\)
but with this lookahead/lookbehind rule just looks for spaces that are attached to the brackets.但是使用这个前瞻/后视规则只查找附加到括号的空格。 How do you modify that to look for every space inside the bracket?
你如何修改它以查找括号内的每个空间?
Thank you in advance!先感谢您!
You can use /\\([^)]* [^)]*\\)/
.您可以使用
/\\([^)]* [^)]*\\)/
。 This matches 0 or more non-closing parentheses characters followed by a space followed by 0 or more non-closing parenthesis characters.这匹配 0 个或多个非右括号字符,后跟一个空格,后跟 0 个或多个非右括号字符。 So it will match
"( )"
and "( )"
but not "()"
.所以它会匹配
"( )"
和"( )"
而不是"()"
。
const s = "() ( test) (test) (test ) ( ) ( ) ( test ) (t est)"; console.log([...s.matchAll(/\\([^)]* [^)]*\\)/g)]);
Simply \\([^()]+\\)
matches everything between a pair of parentheses.只需
\\([^()]+\\)
匹配一对括号之间的所有内容。 That includes spaces, and any other character except (newline or) parentheses.这包括空格和除(换行符或)括号之外的任何其他字符。
(Assuming a regex dialect where literal parens need to be escaped, and plus matches one or more repetitions. Whether a negated character class matches a newline is also dialect-specific.) (假设需要对文字括号进行转义的正则表达式方言,并且 plus 匹配一个或多个重复。否定字符类是否匹配换行符也是特定于方言的。)
If (as you say in a comment) you require at least one space, that's easy to add.如果(如您在评论中所说)您至少需要一个空格,则很容易添加。 Rephrase: match an opening parenthesis character, zero or more non-space, non-parenthesis characters, one space, zero or more non-parenthesis characters (spaces are okay too) until the closing parenthesis.
改写:匹配一个左括号字符、零个或多个非空格、非括号字符、一个空格、零个或多个非括号字符(空格也可以),直到右括号。
\([^ ()]* [^())*\)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.