Regex: matching up to the first occurrence of a word

Go To StackoverFlow.com

5

What is wrong with :

/(?<={).+(?=public)/s

full text

class WeightConvertor {

private:
    double gram;
    double Kilogram;
    double Tonnes;
    void SetGram(double);
    void SetKiloGram(double);
    void SetTonnes(double);
matching end

public:
    WeightConvertor();
    WeightConvertor(double, double, double);
    ~WeightConvertor();
    void SetWeight(double, double, double);
    void GetWeight(double&, double& ,double&);
    void PrintWeight();
    double TotalWeightInGram();

public:

};

how can i match only this text :

private:
    double gram;
    double Kilogram;
    double Tonnes;
    void SetGram(double);
    void SetKiloGram(double);
    void SetTonnes(double);
matching end
2012-04-04 18:07
by faressoft


11

You want a lazy match:

/(?<={).+?(?=public)/s

See also: What is the difference between .*? and .* regular expressions?
(which I also answered, as it seems)

2012-04-04 18:10
by Kobi
That is what I need. Thank - faressoft 2012-04-04 18:13


1

I think you need this:

(?s)(?<={).+?(?=public)

its like the answer posted by Bohemian but its lazy, so it matches what you want.

2012-04-04 18:13
by Robbie


0

You need the "dot matches newline" switch turned on, and a non-greedy (.*?) match:

(?s)(?<={).+?(?=public)

Quoting from the regex bible, the (?s) switch means:

Turn on "dot matches newline" for the remainder of the regular expression.

Note that the slashes around your regex have nothing to do with regex - that's a language thing (perl, javascript, etc) and irrelevant to the actual question

2012-04-04 18:08
by Bohemian
The op already has the /s flag, I think the problem is that the pattern matches until the last public and not the first - Kobi 2012-04-04 18:13
@Kobi Thanks I didn't know that was a switch. I know regex but not perl (I assume - Bohemian 2012-04-04 18:15
Ads