问题描述:

I'm currently using a RegEx like so (.{12}$)|(^.{1,12}$) - something like "if the value is 1 to 12 long, return them, else return the last 12."

I'm looking to add another clause, where if the length is greater than 16, I need to return a subset of it (specifically, starting at the 5th character, return 12).

How can I do this within the same RegEx?

网友答案:

It seems to work with

(?<=^.{4}).{12}|^.{1,12}$

This contains two parts. The first one handles strings at least 16 characters in length. For that it starts matching at the fifth character (that's what the (?<=^.{4}) is for – ensuring that there are exactly four characters preceding). After that there have to be at least 12 characters which are matched.

The second part is just for strings with 1–12 characters, matching the complete string.

Quick PowerShell test:

PS> '12345','1234567890','abcdefghijklmnopqrst'|%{if($_-match'(?<=^.{4}).{12}|^.{1,12}$'){$Matches}}

Name                           Value
----                           -----
0                              12345
0                              1234567890
0                              efghijklmnop
相关阅读:
Top