简体   繁体   English

正则表达式匹配多个出现IFF另一个字符串发生

[英]Regex to match multiple occurances IFF another string occurs

I'm really hoping this can be solved in regex, but I fear not.... 我真的希望这可以在正则表达式中解决,但我不担心....

I'm looking for a regex that will return multiple matches of a term ONLY is another term appears in the same string. 我正在寻找一个正则表达式,只返回一个术语的多个匹配项是另一个术语出现在同一个字符串中。 This is better explained with an example. 用一个例子可以更好地解释这一点。 Consider: 考虑:

The numbers are 144, 424, and 345. Not 45.

I'd like to match '144', '424' and '345' only. 我想只匹配'144','424'和'345'。 (Any 3 digit number) - but only if they follow the term ' numbers ' somewhere before. (任何3位数字) - 但前提是他们在某处遵循“ 数字 ”一词。 So the following aditional example: 以下是附加示例:

The numbers we are looking for: 234 & 992

Should return '234' and '992' only. 应该只返回'234'和'992'。

The following sentence should not match anything: 以下句子不应该匹配任何东西:

Some examples: 234, 244 and 12

I thought I was onto something with the following regex: 我以为我正在使用以下正则表达式:

(?<=numbers\b)(?:.|\n)*?\b(\d{3})\b

But it only matches the first number. 但它只匹配第一个数字。 Is what I'm trying to achieve even possible? 我正在努力实现的目标是什么? No manner of lookahead or lookbehind seems to work here. 没有前瞻或外观的方式似乎在这里工作。 For verious reasons I'm limited to this only being a single regex expression, and I don't have the option to selectivly access individual capturing groups after the fact. 出于各种原因,我仅限于这个只有一个正则表达式,并且我没有选择在事后选择性地访问各个捕获组。 So looking for a purely regex method! 所以寻找纯正的正则表达式方法!

You may use this regex with \\G : 您可以将此正则表达式用于\\G

(?:\bnumbers\b|(?!^)\G).*?\b(\d{3})\b

RegEx Demo RegEx演示

  • \\G asserts position at the end of the previous match or the start of the string for the first match. \\G在上一场比赛结束或第一场比赛的字符串开头处断言位置。
  • (?!^) avoids matching \\G at line start (?!^)避免在行开始时匹配\\G

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

相关问题 正则表达式以匹配字符串的多个实例 - Regex to match multiple instances of a string 计算另一个字符串中的字符串出现次数 - calculating the number of string occurances in another string 正则表达式匹配多行或其他解决方案? - regex match multiple lines or another solution? 将字符串与多个正则表达式模式匹配 - Match a string against multiple regex patterns 使用正则表达式保留首次出现,从String中删除重复的字符 - Remove duplicated characters from String using regex keeping first occurances Java正则表达式匹配至少出现两次的单词 - Java regex to match a word that occurs at least twice Java正则表达式匹配一个特定的字符串或另一个特定的字符串,还是根本不匹配? - Java Regex to match a specific string or another specific string, or not at all? 正则表达式将字符串与另一个字符串Patten匹配,该字符串是/ DIG /? - Regex to match the string with another string Patten which is /DIG/? 当这样的字符串由多行完成时,无法将字符串与正则表达式模式匹配 - Cannot match string with regex pattern when such string is done of multiple lines 是否可以通过正则表达式替换仅在结构顶层多次出现的 json 字符串中的值? - Is it possible to replace a value in a json string that occurs multiple times only at the top level of the structure via regex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM