正则表达式在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"
我的牛总是给牛奶
My cow always gives milk
将返回
always give
"always gives"
这是我到目前为止拼凑的表达式:
Here is the expression I have pieced together so far:
(?=cow).*(?=milk)
然而这返回字符串cow always give
However this returns the string "cow always gives"
推荐答案
前瞻((?= $ c) $ c> part)不消耗任何输入。它是零宽度断言(边界检查和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屋!