JavaScript正则表达式:检测带前缀的方括号内首尾空格问题
Got it, let's work out the right regex for your custom lint rule! I'll break down exactly what you need and how to implement it.
明确匹配规则
First, let's restate your requirements to make sure we're on the same page:
- Trigger errors when there's a prefixed word (can include
-,., or other non-whitespace characters) followed by square brackets with unnecessary spaces inside:foo[ bar](space right after[)foo[bar ](space right before])foo[ bar ](spaces on both ends inside brackets)
- Do NOT trigger errors for:
- Brackets with no prefix (even if they have spaces):
[ bar],[bar ],[ bar ] - Prefixed brackets with no extra spaces:
foo[bar]
- Brackets with no prefix (even if they have spaces):
正则表达式解决方案
Here's a regex that fits all your needs, optimized for JavaScript (works in modern environments like ESLint which supports ES2018+ features):
/(?<=\S)\[\s+|(?<=\S\[.*)\s+\]/g
分解解释
Let's break down what each part does:
(?<=\S)\[\s+:(?<=\S): A positive lookbehind that checks there's a non-whitespace character immediately before the[(this ensures there's a prefix word, not just standalone brackets).\[\s+: Matches[followed by one or more spaces. This catches cases likefoo[ bar].
(?<=\S\[.*)\s+\]:(?<=\S\[.*): A positive lookbehind that checks we have a non-whitespace character followed by[and any characters before this point (again, ensuring a prefix exists).\s+\]: Matches one or more spaces immediately before]. This catches cases likefoo[bar ].
在Lint规则中使用示例
Here's how you might integrate this into a custom ESLint rule (adjust based on your lint tool):
module.exports = { create(context) { return { // Check string literals Literal(node) { if (typeof node.value !== 'string') return; const invalidSpaceRegex = /(?<=\S)\[\s+|(?<=\S\[.*)\s+\]/g; if (invalidSpaceRegex.test(node.value)) { context.report({ node, message: 'Remove unnecessary spaces inside array brackets when using a prefix word.' }); } } }; } };
测试验证
Let's confirm this regex works for your cases:
- ✅ Matches:
foo[ bar],foo[bar ],foo[ bar ] - ❌ Doesn't match:
[ bar],[bar ],[ bar ],foo[bar]
兼容旧环境(如果需要)
If your lint tool doesn't support ES2018 lookbehind assertions, you can use this alternative regex that uses capture groups instead:
/\S+\[\s+|\S+\[.*\s+\]/g
This will match the entire prefixed bracket segment with invalid spaces, which works just as well for reporting errors.
内容的提问来源于stack exchange,提问作者Janez

