简体   繁体   中英

RegEx match another pattern if first pattern fails

Here's the logic I'm failing with: If the input is 14 characters, return characters 9 through 13. Otherwise, return everything.

(?<=^.{8}).{5}(?=.$) works as I'd expect, passing with characters 9 through 13 as the result set. If I append |.* to the RegEx to make (?<=^.{8}).{5}(?=.$)|.* , it always returns everything. I'm obviously going about this incorrectly.

Any input?

^(?=.{14}$).{8}(.*).$|^.*$

Try this .This will return characters from 9 to 13 when string is of 14 characters.See demo.

https://regex101.com/r/pT4tM5/29

我确定正则表达式是必需的,但是由于您仅处理字符串长度,因此也可以使用子字符串

input.Length == 14 ? return input.Substring(8,5) : input;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM