tags:

views:

178

answers:

6

I need some help with regex.

  1. I have a pattern AB.* , this pattern should match for strings like AB.CD AB.CDX (AB.whatever).and so on..But it should NOT match strings like AB,AB.CD.CD ,AB.CD. AB.CD.CD that is ,if it encounters a second dot in the string. whats the regex for this?

  2. I have a pattern AB.** , this pattern should match strings like AB,AB.CD.CD, AB.CD. AB.CD.CD but NOT strings like AB.CD ,AB.CDX, AB.whatever Whats the regex for this?

Thanks a lot.

+1  A: 

Looks like you've got globs not regular expressions. Dot matches any char, and * makes the previous element match any 0+ times.

1) AB\.[^.]* Escape the first dot so it matches a literal dot, and then match any character other than a dot, any number of times.

2) "^(AB)|(AB\.[^.]*\.[^.]*$" This matches AB or AB followed by .<stuff>.<stuff>

Douglas Leeder
I tried with globs , but it also gives true for both case AB.* and AB.**for any string matching AB.whatever ,But my requirements are somewhat refined for * and **
+2  A: 

http://www.regular-expressions.info/ contains lots of useful information for learning about regular expressions.

Stephen Denne
+1  A: 

If your regex engine supports negative lookahead you might try something like:

^AB\.[^.]+$
^AB(?!\.[^.]+$)

(or

^AB\.[^.]*$
^AB(?!\.[^.]*$)

if you want to allow AB. )

it depends
A: 

I don't find you're question entirely clear; please comment here (or edit your question if you can't add comments) if I'm getting this wrong but what I think you're looking for is:

1) matching strings "AB.AnyTextHereWithoutDots" but not "AB" or "AB.foo." etc

If so a matching regex would be:

"^AB\.[^.]*$"

2) matching "AB" or "AB.something.something" with either none or two or more dots

If so a matching regex would be something like:

"^AB(\..*\..*)?$" or "'^AB\(\..*\..*\)\?" (depending on the nature of your regex engine)

As Douglas suggests matching with globs would likely be easier.

And as spdenne suggests, find a good regex reference.

Dave C
A: 

I tried this in vim. Here is the sample data:

AB.CD
AB.CDX
AB.whatever
AB
AB.CD.CD
AB.CD.
AB.CD.CD

Here is my regexes

  1. This captures all lines starting with AB and then expects a literal dot, and then filters out all lines that has a second dot.

    ^AB\.[^.]*$

  2. This captures all lines that is just an AB (the part before the pipe) or lines that start with AB that is followed by two literal dots (escaped with a backslash)

    ^AB$\|^AB\..\..$

jop
A: 

http://regexpal.com/

Have fun :)

davogones