我需要一个正则表达式来获取句子中 [
和 ]
之间的文本。
示例文本:
Hello World - Test[**This is my string**]. Good bye World.
期望的结果:
**This is my String**
我想出的正则表达式是 Test\\[[a-zA-Z].+\\]
,但这会返回整个 **Test[This is我的字符串]**
最佳答案
您可以使用捕获组来访问感兴趣的文本:
\[([^]]+)\]
使用 JavaScript 的快速概念证明:
var text = 'Hello World - Test[This is my string]. Good bye World.'
var match = /\[([^\]]+)\]/.exec(text)
if (match) {
console.log(match[1]) // "This is my string"
}
如果您使用的正则表达式引擎同时支持 lookahead和 lookbehind ,Tim的解决方案比较合适。
关于regex - 使用正则表达式搜索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7950817/