我有一段文本如下,文本中包含一些单词及其含义。我需要使用 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
正则表达式分解:
^
:开始[A-Za-z]+
:匹配1+个英文字母(?:\s+[A-Za-z]+)*
:匹配1+个空格后跟1+个英文字母。重复此组 0 次或更多次。(?=:)
:先行断言我们在下一个位置有:
关于javascript - 如何修改正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74741487/