简体   繁体   English

Reg Ex:重复匹配不同值的模式

[英]Reg Ex: Repeating Patterns that match different values

I'm trying to re-use regex groups for example: 我正在尝试重用正则表达式组,例如:

(?<var>[A-Za-z](\d*\w*)*)

Matches most variable names eg abc , abc123 , abc_123 , abc_123_abc and so on. 最匹配的变量名如abcabc123abc_123abc_123_abc等。

Is there a way I could re-use this group without typing the whole pattern again? 有没有一种方法可以重用该组而无需再次键入整个模式?


For example if I wanted to create a regex to match the below string: 例如,如果我想创建一个正则表达式来匹配以下字符串:

abc_123 AS xyz_89

I would need to create a reg ex like: 我需要创建一个reg ex,例如:

^([A-Za-z](\d*\w*)*)( AS )([A-Za-z](\d*\w*)*)$

And to match something like: 并匹配以下内容:

abc_123.def_456 AS xyz_89

I would need to use the same pattern 3 times. 我将需要使用相同的模式3次。

It would seem more efficient to be able to refer back to the first group so I'm not repeating regex logic. 能够参考第一组似乎更有效,因此我不再重复正则表达式逻辑。 I've read about back referencing but it seems like they are meant for matching the same value rather than general pattern. 我已经阅读了有关反向引用的信息,但似乎它们是为了匹配相同的而不是通用模式。

In php , the recursing sub pattern works: php中 ,递归子模式有效:

^([A-Za-z](?:\d*\w*)*)( AS )(?1)

The above regex will match: 上面的正则表达式将匹配:

abc_123 AS xyz_89

Explanation: 说明:

  1. ([A-Za-z](?:\\d*\\w*)*) Taken from your example and marked as group 1 ([A-Za-z](?:\\d*\\w*)*)来自您的示例并标记为组1
  2. ( AS ) taken from your example, which remains as it is ( AS )取自您的示例,该示例保持不变
  3. (?1) is a recursing sub pattern of the first group (?1)是第一组的递归子模式

Demo 演示

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

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