8

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
faressoft
  • 17,177
  • 42
  • 96
  • 138

3 Answers3

14

You want a lazy match:

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

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

Community
  • 1
  • 1
Kobi
  • 125,267
  • 41
  • 244
  • 277
1

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

Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • 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 Apr 04 '12 at 18:13
  • @Kobi Thanks I didn't know that was a switch. I know regex but not perl (I assume) – Bohemian Apr 04 '12 at 18:15
1

I think you need this:

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

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

Robbie
  • 16,416
  • 3
  • 35
  • 43