【问题标题】:RegEx for capturing words in parenthesesRegEx 用于捕获括号中的单词
【发布时间】:2019-05-23 21:21:53
【问题描述】:

这是我的正则表达式:

/(\(-caramel-\)|\(-vanilla-\)|)/

使用这个正则表达式,这将只检测到 first string 这是(-caramel-) only

如何检测字符串中的所有(-caramel-)和(-vanilla-)?

这是我的示例字符串:

(-caramel-) John Cina (-vanilla-)(-caramel-)2019-05-19 07:31:05(-vanilla-)

我该如何解决这个问题?

【问题讨论】:

  • 您在示例中以多种方式拼写“香草”,这是故意的吗?
  • nopee..sry my false , gunna 编辑它..
  • 对不起,我拼错了 vanilla..

标签: php regex string preg-match-all regex-group


【解决方案1】:

如果我们希望在搜索中出现拼写错误的单词,我们可以使用字符列表来实现,从左到右以() 为界,可能类似于:

\([carmel-]+\)|\([vanila-]+\)

DEMO

正则表达式

如果不需要此表达式,可以在 regex101.com 中修改或更改。

正则表达式电路

jex.im 可视化正则表达式:

测试

$re = '/\([carmel-]+\)|\([vanila-]+\)/m';
$str = '(-caramel-) John Cina (-vanilla-)(-caramel-)2019-05-19 07:31:05(-vannila-)';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

演示

这个 sn-p 只是表明如果表达式有效:

const regex = /\([carmel-]+\)|\([vanila-]+\)/gm;
const str = `(-caramel-) John Cina (-vanilla-)(-caramel-)2019-05-19 07:31:05(-vannila-)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

【讨论】:

  • 哇,这个 stackoverflow 社区太棒了! O_O 非常感谢艾玛通过编辑我草率的问题进行澄清,您也提供了答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多