简体   繁体   English

在其他两个不同字符串之间匹配字符串

[英]Match string between two other different strings

Another regex question: 另一个正则表达式问题:

I'd like to capture text that exists between two different marker strings. 我想捕获两个不同标记字符串之间存在的文本。 The thing is, the marker strings have a few options. 事实是,标记字符串有一些选择。 For example: 例如:

I'm very hungry for a sandwich and tomorrow I'll go to the store - capturing between "I'm very hungry" and "and" 我非常想吃三明治 ,明天我去商店-在“我非常饿”和“和”之间捕捉

I'm very tired so I'll go to sleep . 我很累, 所以我要去睡觉 - capturing between "I'm very tired" and ".". -在“我很累”和“。”之间进行捕捉。

I'm coding in Javascript, and I thought: 我正在用Javascript编码,我想:

/string one(.*?)string two|\.|string three|string four/gi

But that doesn't seem to work. 但这似乎不起作用。 It just grabs between string one and string two ignoring string three and string four . 它只是在string onestring two之间抓取而忽略了string threestring four

What am I doing wrong with the regex? 正则表达式我在做什么错?

maybe you need to group strings because | 也许您需要对字符串进行分组,因为| has low precedence 优先级低

/string one(.*?)(?:string two|\.|string three|string four)/gi

Edit: adding parentheses changes precedence because the expression in parentheses is evaluated before the rest of the expression. 编辑:添加括号会更改优先级,因为括号中的表达式会先于表达式的其余部分求值。 In addition, here we use non-capturing groups because we use the (?: syntax. 另外,这里我们使用非捕获组,因为我们使用(?:语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM