正则表达式:如果单词中的元音顺序出现(aeiou),则匹配;如果不存在char,则不匹配

时间:2019-05-18 18:19:36

标签: regex regex-lookarounds

我正在尝试匹配单词是否具有aeiou且必须按aeiou的顺序进行匹配。如果有一个不是单词的字符,也不应匹配。例如:

匹配:

cabeilous

不匹配:

sacrilegious 
jeious 
cabeil-ous

这是我到目前为止所拥有的:

.a[^e]*e[^i]*i[^o]*o[^u]*u.

这与sacrilegious上的匹配。

3 个答案:

答案 0 :(得分:1)

如果这是您真正想要的,则必须排除每个否定语中的所有其他元音。

答案 1 :(得分:1)

/^[^\Waeiou]*a[^\Waeiou]*e[^\Waeiou]*i[^\Waeiou]*o[^\Waeiou]*u[^\Waeiou]*$/

应该可以解决问题。锚定字符串的两侧,并排除所有非单词字符和任何不适当的地方。通过将每个元音从紧随其后的字符类中排除,可以允许诸如aeeiou之类的重复。

const pattern = /^[^\Waeiou]*a[^\Waeiou]*e[^\Waeiou]*i[^\Waeiou]*o[^\Waeiou]*u[^\Waeiou]*$/;

[
  "cabeilous",    // yep
  "sacrilegious", // nope
  "jeious",       // nope
  "cabeil-ous",   // nope
  "aaeiou",       // nope
  "aeeiou",       // nope
  "aeiiou",       // nope
  "aeioou",       // nope
  "aeiouu",       // nope
].forEach(test => console.log(test, pattern.test(test)));

const patternWithReps = /^[^\Waeiou]*a[^\Weiou]*e[^\Waiou]?i[^\Waeou]*?o[^\Waeiu]*?u[^\Waeio]*$/;

console.log("\n~~ with repetition: ~~");

[
  "cabeilous",    // yep
  "sacrilegious", // nope
  "jeious",       // nope
  "cabeil-ous",   // nope
  "aaeiou",       // yep
  "aeeiou",       // yep
  "aeiiou",       // yep
  "aeioou",       // yep
  "aeiouu",       // yep
].forEach(test => console.log(test, patternWithReps.test(test)));

答案 2 :(得分:1)

此表达式可以帮助您传递所需的输出,并使其他输出失败:

^([a-z]+)?(?:[a-z]*a(?:[a-z]*e(?:[a-z]*i(?:[a-z]*o(?:[a-z]*u)))))([a-z]+)?$

在这里,我们可以使用逐层体系结构按顺序检查每个字母,然后可以为希望添加的字符添加字符列表。我只是假设[a-z]可能是所需的char列表。

enter image description here

RegEx

如果这不是您想要的表达式,则可以在regex101.com中修改/更改表达式。

RegEx电路

您还可以在jex.im中可视化您的表达式:

enter image description here

用于捕获组的JavaScript演示

const regex = /^([a-z]+)?(?:[a-z]*a(?:[a-z]*e(?:[a-z]*i(?:[a-z]*o(?:[a-z]*u)))))([a-z]+)?$/gm;
const str = `aeiou
cabeilous
zaaefaifoafua
sacrilegious 
jeious 
cabeil-ous`;
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}`);
    });
}