61

I am trying to write a regex that selects everything between two characters.

For example, when the regex encounters a '§' I want it to select everything after the '§' sign, up until the point that the regex encounters a ';'. I tried with a lookbehind and lookahead, but they don't really do the trick.

So for example " § 1-2 bla; " should return " 1-2 bla".

Any help would be greatly appreciated!

Peter Boughton
  • 110,170
  • 32
  • 120
  • 176
Jaaq
  • 611
  • 1
  • 5
  • 6
  • 3
    Please specify the technology in which you are working, as regex has many "flavours" with slightly different syntaxes and capabilities. – Jay Jul 26 '10 at 14:08
  • 1
    Wait, I missed this first time around... "I tried with a lookbehind and lookahead, but they don't really do the trick." -- why not? what went wrong? Is this JavaScript? – Peter Boughton Jul 26 '10 at 14:54
  • 2
    Because I'm new to RegEx and couldn't really figure it out.. It's RegEx in Actionscript 3, and it does really weird things from time to time :) thanks for your answers everyone, I kind of got things working ! – Jaaq Jul 27 '10 at 07:50

4 Answers4

70

How about

"§([^;]*);"

The selected characters between the § and ; are available as match group 1.

mdma
  • 56,943
  • 12
  • 94
  • 128
43

Use this regex

(?<=§).*?(?=;)
Gopi
  • 10,073
  • 4
  • 31
  • 45
19

For a simple case this should do:

§(.*);

It might need to be modified if you don't want to allow nesting:

§(.*?);
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
10

If you have multiple § (char example) use : §([^§]*)§

It will ignore everything between two § and only take what's between the 2 special char, so if you have something like §What§ kind of §bear§ is best, it will output: §what§ , §bear§

What happening? lets dissect the expression § then ([^§]*) then §

  1. 1- match § char
  2. 2- match anything but § [^§] 0 or more times *
  3. match § char

Hope it helps !

FlyingZipper
  • 701
  • 6
  • 26