tags:

views:

84

answers:

2

I try to find methods that have expression createNamedQuery

I try

public[\d\D]*?createNamedQuery

but it finds the first method, but i want the method that has expression createNamedQuery

+1  A: 

I'm guessing that your problem is that you cannot find all of them, but rather just the first one. The way to retreive all of them is different from language to language. For instance, in Python, one would do something similar to the following:

import re

my_data = "some long piece of data that may or may not contain what you're looking for."

for match in re.findall("public[\d\D]*?createNamedQuery", my_data):
    if m is not None:
        print "A match found at position %s" % m.start()

Basically, just try to FindAll. Doing a single Match will only give you the first one.

Evan Fosmark
A: 

If you're trying to find the shortest sequence that starts with "public" and ends with "createNamedQuery", using a non-greedy quantifier isn't good enough. That will just match from the first occurrence of "public" to the first (subsequent) occurrence of "createNamedQuery". To find the shortest sequence, you have to make sure the part between the two sentinels ("public" and "createNamedQuery") can't match the first sentinel again. Here's one way:

public(?:(?!public).)*?createNamedQuery

This isn't the fastest or most robust regex, just the simplest way (I think) to demonstrate the principle. Depending on which regex flavor you're using, I would make use of word boundaries (most flavors) and either atomic groups (Perl, .NET) or possessive quantifiers (Java, PHP, JGSoft).

Alan Moore