在Javascript中获取两个字符串之间的字符串的正则表达式 [英] Regular expression to get a string between two strings in Javascript
问题描述
我发现了非常相似的帖子,但我在这里无法完全理解我的正则表达式.
I have found very similar posts, but I can't quite get my regular expression right here.
我正在尝试编写一个正则表达式,它返回一个介于其他两个字符串之间的字符串.例如:我想获取位于字符串cow"和milk"之间的字符串.
I am trying to write a regular expression which returns a string which is between two other strings. For example: I want to get the string which resides between the strings "cow" and "milk".
我的奶牛总是产奶
会回来
总是给予"
这是我目前拼凑的表达方式:
Here is the expression I have pieced together so far:
(?=cow).*(?=milk)
然而,这将返回字符串cow always Gives".
However, this returns the string "cow always gives".
推荐答案
前瞻((?=
部分)不消耗任何输入.它是一个零宽度断言(边界检查和lookbehinds也是如此).
A lookahead (that (?=
part) does not consume any input. It is a zero-width assertion (as are boundary checks and lookbehinds).
您想要在这里进行常规匹配,以消耗 cow
部分.要捕获两者之间的部分,请使用捕获组(只需将要捕获的模式部分放在括号内):
You want a regular match here, to consume the cow
portion. To capture the portion in between, you use a capturing group (just put the portion of pattern you want to capture inside parenthesis):
cow(.*)milk
根本不需要前瞻.
这篇关于在Javascript中获取两个字符串之间的字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!