admin管理员组

文章数量:1391943

So, I have a regex problem I'm trying to solve and can't figure out.

I need to find a string that starts with R or K, but not followed by a P, continuing onwards til it finds another R or K which isn't followed by a P, with a "&" symbol in between the two.

For example, "RQKRQEQERPELAEG&EQSEKQERPLEQRD" should find the string "RQEQERPELAEG&EQSEK". However, I can't do it, and I don't know how. Help please.

I tried using negative lookbehind and positive lookbehind and all sorts of other shit, and I can't figure it out.

So, I have a regex problem I'm trying to solve and can't figure out.

I need to find a string that starts with R or K, but not followed by a P, continuing onwards til it finds another R or K which isn't followed by a P, with a "&" symbol in between the two.

For example, "RQKRQEQERPELAEG&EQSEKQERPLEQRD" should find the string "RQEQERPELAEG&EQSEK". However, I can't do it, and I don't know how. Help please.

I tried using negative lookbehind and positive lookbehind and all sorts of other shit, and I can't figure it out.

Share Improve this question asked Mar 14 at 8:14 user29974491user29974491 29 10
  • What kind of regex pattern you had tried? In what programming language? – Dhana D. Commented Mar 14 at 9:00
  • It looks like you are looking for the shortest match, which is challenging. If you are using PCRE and expect only one match per line, you could prepend .* to consume the beginning and \K to reset with some regex like ^.*\K[RK](?!P)[A-Z]*&[A-Z]*?[RK](?!P) – bobble bubble Commented Mar 14 at 9:50
  • This question is similar to: Learning Regular Expressions. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Biffen Commented Mar 14 at 11:00
  • 2 why is the match for your sample not RQKRQEQERPELAEG&EQSEK ? – jhnc Commented Mar 14 at 19:27
  • 1 @Fravadona because the question seems to ask for shortest match (second paragraph combined with sample result that excludes leading RQK (which I queried above)). Maybe: [KR](&|[KR]P&|[^KRP&]([KR]P|[[^KR])*&)([KR]P|[^KR])*[KR]([^P]|$) – jhnc Commented Mar 15 at 20:08
 |  Show 5 more comments

2 Answers 2

Reset to default 2

You don't specify a regex flavour so I shall assume PCRE2. With whitespace for legibility:

(?x)
  (?&delim) 
  (?&hasamp)
  (?&delim)
(?(DEFINE) 
  (?<delim> [KR](?!P) )
  (?<other> [KR](?=P) | [^KR] )
  (?<hasamp> (?&other)* & (?&other)* )
)

https://regex101/r/dVPOzg/1

Since no kind of regular expression was specified, I'll use PCRE (or Python, or ECMAScript, or Java 8, or.NET 7.0 (C#)).

[KR](?:[^KR]|.(?=P))*&.*?[KR](?!P)

https://regex101/r/huVaTT/1

本文标签: