使用正则表达式匹配字符串中的后续序列

时间:2018-10-25 12:10:52

标签: javascript regex

我正在尝试从字符串中提取日期和时间部分的占位符。乍一看似乎很简单,但是我在匹配后续序列时遇到了麻烦。

这是两个测试字符串:

  • home at hh:mm:ss for dinner with Bob
  • home at h:m:s for dinner with Bob

我只想匹配占位符中的“ h”,“ m”和“ s”。在这种情况下,它们被分组在一起,但它们也可能散布开来。

我的第一次尝试是匹配所有的'h','m'和's'字符

const
  tests = ['home at hh:mm:ss for dinner with Bob', 'home at h:m:s for dinner with Bob'],
  regex = /(h+|m+|s+)/g;
  
tests.forEach((test, index) => {
  console.group(`test ${index}`);
  let match;
  while (match = regex.exec(test)) {
    console.log(match[1], match.index);
  }
  console.groupEnd();
});

这也匹配“ home”中的“ h”和“ m”以及“ with”中的“ h”。为了防止这种情况的发生,我想修改正则表达式以停止匹配单词中的字符。

const
  tests = ['home at hh:mm:ss for dinner with Bob', 'home at h:m:s for dinner with Bob'],
  regex = /(h+|m+|s+)(?:$|\W|\s)/g;
  
tests.forEach((test, index) => {
  console.group(`test ${index}`);
  let match;
  while (match = regex.exec(test)) {
    console.log(match[1], match.index);
  }
  console.groupEnd();
});

此更改是朝正确方向迈出的一步。 “ home”中的字符不再匹配,但“ with”中的“ h”仍由正则表达式匹配。这就是我被困住的重点。我试图修改正则表达式来处理这种情况,但没有成功。这是我最近的尝试:

const
  tests = ['home at hh:mm:ss for dinner with Bob', 'home at h:m:s for dinner with Bob'],
  regex = /(?:^|\W|\s)(h+|m+|s+)(?:$|\W|\s)/g;
  
tests.forEach((test, index) => {
  console.group(`test ${index}`);
  let match;
  while (match = regex.exec(test)) {
    console.log(match[1], match.index);
  }
  console.groupEnd();
});

它不再与“ with”中的“ h”匹配,但现在也不再与“ hh:mm:ss”中的“ mm”匹配。

有人可以帮助我解决我要构造的正则表达式吗?

0 个答案:

没有答案