javascript - 正则表达式获取 () 之间的字符串

标签 javascript regex

我有文字

   var text =  (hello) world this is (hi) text

我想编写一个正则表达式函数,这样我就可以得到

parseText(text) // returns ['hello', 'hi']

我尝试过这个但不起作用:

'(hello) world this is (hi) text'.match('((.*?))')

感谢您的帮助

最佳答案

你可以尝试: /\([^\)]+\)/g

  1. \(:转义字符
  2. [^\)]+:一个或多个字符(包括符号)直到)个字符。
  3. \):转义字符
  4. g 标志:搜索所有巧合

enter image description here

const regex = /\([^\)]+\)/g;
const str = `(hello) world this is (hi) text`;

console.log(
  str.match(regex) // this returns an string array
    .map(i => i.slice(1, -1)) // remove first and last char
);

提示:

About point #2, you can change to [\)]* to take effect over zero or more character.

If you need only string, you can use \w+ or \w*.

If you need only words you can use /\(\b\w+\b\)/g

关于javascript - 正则表达式获取 () 之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63993059/

相关文章:

javascript - 在js sdk中手动设置访问 token

javascript - 在 Javascript 中比较值与前导零

javascript - 替换 JavaScript 中的函数

正则表达式匹配而不考虑间距

javascript - 即使相对位置也将元素设置为特殊坐标?

javascript - 图像 slider - 移动和桌面的不同图像

javascript - 从 url 中删除所有空值

regex - 正则表达式搜索并替换YouTube短代码

Ruby linkify 用于字符串中的 url

java - 检查字符串是否包含 CJK(中文)字符