Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: matching up to the first occurrence of a word [duplicate]

Tags:

regex

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
like image 254
faressoft Avatar asked Apr 04 '12 18:04

faressoft


People also ask

What does \b mean in regex?

The \b metacharacter matches at the beginning or end of a word.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

What does regex (? S match?

Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

How do you repeat in regex?

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.


3 Answers

You want a lazy match:

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

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

like image 73
Kobi Avatar answered Oct 08 '22 20:10

Kobi


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

like image 30
Bohemian Avatar answered Oct 08 '22 21:10

Bohemian


I think you need this:

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

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

like image 25
Robbie Avatar answered Oct 08 '22 21:10

Robbie