How to match all words but one?
-
16-06-2021 - |
Pergunta
I'm trying to match expressions that start with PRE and end with PRE. I'm looking for a lazy match, that is the ending PRE in the matched expression should be the first one found after the starting PRE. I was trying to achieve this with a negative lookahead regex, testing on RegExr:
Regex:
PRE(\w|\s)+(?!PRE)
Expression to match:
PRE erp PRE edas PRE
The expression above is matched in full by the given regex, while I had expected only to match PRE erp PRE. Please suggest a regex that lazily matches expression starting and ending with PRE.
Solução
"(PRE)(.*?)(PRE)"
This works for me in my (C#) code, returning one match, PRE erp PRE.
var codeBlocks = Regex.Matches("PRE erp PRE edas PRE", "(PRE)(.*?)(PRE)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
MessageBox.Show("Matches found: " + codeBlocks.Count.ToString() + "\nMatch: " + codeBlocks[0].Value);
Outras dicas
Supposed your language support lazy matching (if it supports look-around, I suppose it also supports lazy quantifier):
PRE(.*?)PRE
As this answer may be wrong, please specify your language next time. Regex has different set of features for different the languages.