javascript - 如何修改正则表达式

标签 javascript regex

我有一段文本如下,文本中包含一些单词及其含义。我需要使用 Javascript 正则表达式方法获取这些单词。例如,如果我在下面给出文本,那么返回的单词应该是 Necessity、Lay of the land 和 Mumble

Necessity:(noun)the need for something, or something that is needed Example: In my work, a computer is a necessity.

Lay of the land: (idiom n. Or v.)the general state or condition of affairs under consideration; the facts of a situation Example: We asked a few questions to get the lay of the land

Mumble:(verb) to speak quietly or in an unclear way so that the words are difficult to understand Example: She mumbled something about needing to be home, then left.

我的编码如下,但它没有按预期工作。

let text = `Necessity:(noun)the need for something, or something that is needed
Example: In my work, a computer is a necessity.

Lay of the land: (idiom n. Or v.)the general state or condition of affairs under consideration; the facts of a situation
Example: We asked a few questions to get the lay of the land.

Mumble:(verb) to speak quietly or in an unclear way so that the words are difficult to understand
Example: She mumbled something about needing to be home, then left.
`;

let matches = text.match(/[A-Za-z]+(?=\:\S)/g);

console.log(matches); //['Necessity', 'Mumble']

我可以知道我错过了什么吗?任何帮助将不胜感激。

最佳答案

你可以使用这个正则表达式:

/^[A-Za-z]+(?:\s+[A-Za-z]+)*(?=:)/gm

RegEx Demo

正则表达式分解:

  • ^:开始
  • [A-Za-z]+:匹配1+个英文字母
  • (?:\s+[A-Za-z]+)*:匹配1+个空格后跟1+个英文字母。重复此组 0 次或更多次。
  • (?=:):先行断言我们在下一个位置有 :

关于javascript - 如何修改正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74741487/

相关文章:

javascript - 使用 PhantomJS 下载网页

javascript - 如何使用haxe创建可重用的js库?

python - sre_constants.错误: unexpected end of regular expression - Should Work Fine

ruby - 从字符串中提取几个数字中的一个

删除第二个空格后的文本

regex - 从纯文本日志文件中提取 xml block

javascript - parseInt 不适用于 window.document

javascript - WinJS 绑定(bind)未更新

c# - 正则表达式检测连字符

javascript 在 10 分钟内监听 http post 请求,如果没有则取消它