tags:

views:

225

answers:

5

Hi. Can someone provide me with a regular expression that will find this string : <% but will exclude this string : <%@ Thanks.

+1  A: 

How about this one

<%([^@]|$)

It matches the end of the string or [^@], which is a character class containing all characters except @

amarillion
That will match more than <% .It will include the character after <%
Philippe Leybaert
That doesn't matter for the question at hand - it properly distinguishes <% and <%@ like the asker wanted.
amarillion
+4  A: 

If you're using .NET, the regular expression you're looking for is:

<%(?!@)

It will also work in non-.NET applications, but some regular expression implementations don't support (?!)

Philippe Leybaert
This would be the best solution, capturing only the <% and nothing else.
avdgaag
It also works in perl like regex implementations.
Nikolai Ruhe
+2  A: 

The exact correct answer varies between different regex syntaxes, but something like this should work:

<%[^@]

or perhaps this, if your regex syntax allows:

<%([^@]|$)

The latter will also match an occurrence of <% at the end of the string (or line), whereas the first regex probably won't.

Finally, as other posters suggest, this might work too if your regex language has "zero-width negative look-ahead assertions" (like Perl and C#):

<%(?!@)
Ville Laurikari
That will match more than <% .It will include the character after <%
Philippe Leybaert
That is true, although arguably it does not matter. <% is a constant string, so it's enough to find the starting location for it. If you only want to know whether <% is present (but not <%@), it doesn't matter either.
Ville Laurikari
A: 

Thanks all for your replies. I'm using the file search box in Eclipse, which probably uses a Java-based regexp implementation. I've tested al answers above and they seem to work. Can I ask a 2nd question ? How do I exclude both <%@ and <%- ? Thanks.

A: 

Based on your updated request, either of these will work:

<%(?!@|-)

<%(?![@-])
Peter Boughton
Shouldn't it be this ? <%(?!(@|-))
Argh, yes, it should. Fixed.
Peter Boughton