我正在尝试找出如何编写一个正则表达式来匹配这个模式
测试1003##$%#测试
汉字+非汉字+汉字,非汉字可以是任何字符,汉字总是一样的(测试)。
我知道我们可以使用^((?!(\p{Han}).)*$来匹配非中文字符。但不确定如何确保头部和尾部始终是相同的中文字符(在本例中为测试)。
发布于 2021-11-17 23:40:54
如果应该至少有一个除\p{Han}之外的字符,则可以匹配\P{Han}。
捕获捕获组1中的\p{Han}字符,并在组1的末尾添加一个反向引用。
^(\p{Han}+)\P{Han}.*\1$^ string(\p{Han}+)捕获组1的开始,匹配script\P{Han}中的至少一个\p{Han}.*以外的字符匹配string\1$的其余部分匹配字符串末尾的组1的反向引用要也只匹配测试,您可以使用:
^(\p{Han}+)(?:\P{Han}.*\1)?$发布于 2021-11-18 00:02:30
使用
^(\p{Han}+)\P{Han}*\g{1}$参见regex proof。
说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\p{Han}+ Chinese characters
(1 or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\P{Han} non-word Chinese characters (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\g{1} matches the same text as most recently matched
by the 1st capturing group
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string如果prefix = suffix = 测试,则使用
^测试\P{Han}*测试$或者,如果后缀和前缀可以包含更多中文字符:
^测试\p{Han}*\P{Han}*\p{Han}*测试$https://stackoverflow.com/questions/70012840
复制相似问题