是否可以定义一个模式并重用它来捕获多个组? [英] Is it possible to define a pattern and reuse it to capture multiple groups?

查看:41
本文介绍了是否可以定义一个模式并重用它来捕获多个组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以定义模式的一部分然后或许命名它以便它可以在主模式中多次重复使用而不必再次写出来?

Is it possible to define a part of the pattern once then perhaps name it so that it can be reused multiple times inside the main pattern without having to write it out again?

要画图,我的模式看起来类似于这个(伪正则表达式模式)

To paint a picture, my pattern looks similar to this (pseudo regex pattern)

(PAT),(PAT), ... ,(PAT)

其中 PAT 是一些冗长的模式.

Where PAT is some lengthy pattern.

要求

  1. 不必重复模式,因为它的长度成为一个问题(目前,Notepad++ 在使用正则表达式时只允许搜索框中有 2047 个字符,我很容易超过这个限制)
  2. 每个捕获组都应该能够独立于其同级进行匹配.例如,假设我的模式是 ([az]),([az]),([az]) 然后 a,a,aa,b,c 应该匹配
  1. Not have to repeat the pattern because it's length becomes a problem (currently, Notepad++ only allows 2047 characters in the search box when using regex and I'm easily going over this limit)
  2. Each capturing group should be able to match independently of its siblings. For example, say that my pattern is ([a-z]),([a-z]),([a-z]) then a,a,a and a,b,c should match

我曾考虑命名第一个捕获组,然后在后续捕获组中引用它,但此方法违反了第二个要求(即,它无法匹配 a,b,c).是否有直接或间接的方式仅使用正则表达式来满足这两个要求?

I've looked into naming the first capturing group then referencing it in the subsequent capturing groups but this method breaks the second requirement (i.e., it fails to match a,b,c). Is there a direct or indirect way of fulfilling both requirements using regex only?

我的最终目标是能够获取和访问每个捕获组的值,以便我可以稍后在搜索和替换的替换"部分操作每个组.更换盒子.

My end goal is to be able to get and access the value of each capturing group so I can manipulate each group later in the "replace" part of the search & replace box.

推荐答案

要重用模式,您可以使用 (?n) 其中 n 是组重复.例如,您的实际模式:

To reuse a pattern, you could use (?n) where n is the number of the group to repeat. For example, your actual pattern :

(PAT),(PAT), ... ,(PAT)

可以替换为:

(PAT),(?1), ... ,(?1)

(?1)(PAT) 的模式相同,无论 PAT 是什么.

(?1) is the same pattern as (PAT)whatever PAT is.

您可能有多个模式:

(PAT1),(PAT2),(PAT1),(PAT2),(PAT1),(PAT2),(PAT1),(PAT2)

可以简化为:

(PAT1),(PAT2),(?1),(?2),(?1),(?2),(?1),(?2)

或:

((PAT1),(PAT2)),(?1),(?1),(?1)

或:

((PAT1),(PAT2)),(?1){3}

这篇关于是否可以定义一个模式并重用它来捕获多个组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆