javascript - 如何使用正则表达式从括号中取出单词
问题描述
我想使用正则表达式从括号中取出单词。
这是我的代码:
var patt = /(?!.+\))\w+/g;
var str = '( hello ) ehsan (how are) you' ;
console.log( patt.exec(str) ) ;
console.log( patt.exec(str) ) ;
实际结果
you , null
预期结果
ehsan , you
有没有办法通过负前瞻?
解决方案
您的正则表达式使用负前瞻(?!.+\)
来断言右侧的内容不是右括号。这与最后一次出现的右括号匹配,因为在那之后,没有更多的)
。然后你匹配 1+ 个单词字符,这些字符将匹配you
.
您可以使用捕获组,而不是使用负前瞻:
\([^)]+\)\s*(\w+)
const regex = /\([^)]+\)\s*(\w+)/g;
const str = `( hello ) ehsan (how are) you`;
let m;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m[1]);
}
如果引擎支持lookbehind并接受无限长度的量词,您也可以使用正向lookbehind:
(?<=\([^()]+\)) (\w+)
const regex = /(?<=\([^()]+\))\s*(\w+)/g;
const str = `( hello ) ehsan (how are) you`;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m[1]);
}
推荐阅读
- hibernate - 为什么 merge() 返回副本对象?
- flutter - Flutter - showDatePicker 将一周的第一天设置为星期一
- spring - 百里香+春天。使用对象方法而不是表单中的另一个块
- c - 如何确保二维数组在内存中连续分配
- c# - 使用无服务器和 AWS API 网关从 ASP .Net Core MVC 返回二进制数据
- elasticsearch - java - 如何使用java Hight level rest客户端在弹性搜索中执行范围查询?
- python - 我已经编写了合并排序的代码。但是我无法返回排序值如何返回排序列表
- github-api - 通过存储库调度事件触发时如何在工作流中指定 event_type
- html - 在我部署我的项目后,他找不到图像和日志
- go - 如何实现子路由