简体   繁体   中英

How can i match inner expression on nested expression with regular expressions?

I got this code on c#

This works:

string code = "dqwdSTART12sdaSTART12312ENDsdfSTARTasdsaENDasdaENDqwe";
string pattern = "START[^(START)(END)]*END";

But not this:

string code = "dqwdstart12sdastart12312endsdfstartasdsaendasdaendqwe";
string pattern = "start[^(start)(end)]*end";

How can i do the match ?

( preferably c # )

this pattern [^(start)(end)] does not mean what you think, it does not mean non of the words but non of the characters enclosed between [ and ]
the only reason why it worked is because you had numbers between start and end , if you add a letter like s it won't work.

use this pattern instead

START((?:(?!START|END).)*)END

with gi options Demo

START           # "START"
(               # Capturing Group (1)
  (?:           # Non Capturing Group
    (?!         # Negative Look-Ahead
      START     # "START"
      |         # OR
      END       # "END"
    )           # End of Negative Look-Ahead
    .           # Any character except line break
  )             # End of Non Capturing Group
  *             # (zero or more)(greedy)
)               # End of Capturing Group (1)
END             # "END"
(?<=start)(?:(?!start|end).)*(?=end)

You can try this as well if you dont want to capture start and end and just the content between.See demo,

http://regex101.com/r/yP3iB0/23

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