且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以定义一个模式并重用它来捕获多个组?

更新时间:2023-10-09 21:40:16

要重用模式,您可以使用 (?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}