匹配正则表达式中的重复子串 [英] Matching on repeated substrings in a regex

查看:57
本文介绍了匹配正则表达式中的重复子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个正则表达式是否可以根据同一正则表达式的其他部分进行匹配?

Is it possible for a regex to match based on other parts of the same regex?

例如,无论字符是什么,我如何匹配以相同的 3 个字符序列开始和结束的行?

For example, how would I match lines that begins and end with the same sequence of 3 characters, regardless of what the characters are?

匹配:

abcabc
xyz abc xyz

不匹配:

abc123

未定义:(可以匹配或不匹配,以最简单的为准)

Undefined: (Can match or not, whichever is easiest)

ababa
a

理想情况下,我想要 perl regex 风格的东西.如果这是不可能的,我很想知道是否有任何口味可以做到这一点.

Ideally, I'd like something in the perl regex flavor. If that's not possible, I'd be interested to know if there are any flavors that can do it.

推荐答案

使用捕获组和反向引用.

Use capture groups and backreferences.

/^(.{3}).*\1$/

\1 指回与第一个捕获组的内容(() 的内容)匹配的任何内容.大多数语言中的正则表达式允许这样的事情.

The \1 refers back to whatever is matched by the contents of the first capture group (the contents of the ()). Regexes in most languages allow something like this.

这篇关于匹配正则表达式中的重复子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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