views:

155

answers:

5

I'm trying to use a regular expression to find all substrings that start with an equals sign (=) and ends with a semicolon (;) with any number of characters in between. It should be something like this =*;

For some reason, the equals is not registering. Is there some sort of escape character that will make the regex notice my equals sign?

I'm working in Java if that has any bearings on this question.

Thanks!

+6  A: 

This looks for "any number of = signs, including 0"

=*;

If you want "= followed by any number of other characters" you want

=.*;

However, that will match greedily - if you want lazy matching (so that it stops one group when it finds the next semicolon) you might want:

=.*?;
Jon Skeet
+1  A: 

The regex you provided would match ;, ===;, ..., ================;. How about =.*; (or =.*?; if non-greedy is needed)?

Marcel J.
+5  A: 

This may be what you are looking for. You need to specify a character set or wild card character that you are applying the asterisk to.

"=([^;]*);"

You can also use the reluctant quantifier:

"=(.*?);"

Using the parenthesis you now have groups. I believe the first group is the whole entire match, and group[1] is the group found within the parenthesis.

The code may look something like:

Regex r = new Regex("=([^;]*);");
Match m = r.Match(yourData);
while (m.Success) {
    string match = m.Groups[1];
    // match should be the text between the '=' and the ';'.
}
jjnguy
This got me what I was looking for, but is it possible to find only what's between those delimiters? In other words, I want to get what's between the = and ; without actually including them in the expression.Thanks
chama
If you add parens around the value you want to find, you can use one of Matcher's group() methods to retrieve just the bit in parens.
Matt Kane
How exactly would I use the group() method to do this?
chama
@chama I added some info that may be helpful about groups
jjnguy
A: 

Something like =.*;

Martin Milan
+1  A: 

An excellent source for learning about regexp in Java: sun's book about regexp

crunchdog