32

How can I match all characters between 2 specified characters, say " " -> from sdfsf " 12asdf " sdf

I want to get 12asdf only.

Burgi
  • 421
  • 8
  • 24
dave
  • 321
  • 1
  • 3
  • 3
  • 1
    What were you hoping to get? Is it not returning the leading whitespace? Show us the regex you are using and put your example results in a code block, please. – Robusto Mar 08 '10 at 16:27

4 Answers4

94

You can use the following pattern to get everything between " ", including the leading and trailing white spaces:

"(.*?)"

or

"([^"]*)"

If you want to capture everything between the " " excluding the leading and trailing white spaces you can do:

"\s*(.*?)\s*"

or

"\s*([^"]*)\s*"
Bibek Lekhak
  • 61
  • 1
  • 7
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • Agreed. Make sure to look up anything you can find on "non-greedy" (vs. "greedy") expressions. Should be an interesting read if you don't know it yet. And it will surely make your life with regexes easier if you know the difference. – exhuma Mar 08 '10 at 16:38
  • 1
    Through my testing these actually don't get the inner characters excluding the quotations, like the question asked. These do however include the quotations too! – cody.codes Oct 06 '18 at 17:37
  • 1
    Like others have said, this doesn't answer the question, it gets the text WITH the quotes. – Hasen Apr 28 '19 at 05:47
10

I suggest you use

(?<=")(?:\\.|[^"\\])*(?=")

This will match only what is between the quotes (not the quotes themselves) and also handle escaped quotes inside your string correctly.

So in "She said, \"Hi!\"", it will match She said, \"Hi!\".

If you're using JavaScript or Ruby (which you didn't mention) and therefore can't use lookbehind, use

"((?:\\.|[^"\\])*)"

and work with the capturing group no. 1.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

You can use preg_match(/"([^"]*)"/,$input,$matches);. $matches[1] will have what you want.

AlG
  • 14,697
  • 4
  • 41
  • 54
Joseph
  • 281
  • 2
  • 10
0
[^"].*[^"]

If you enter: "Elie", it will give Elie (note: without quotes)

Taryn
  • 242,637
  • 56
  • 362
  • 405
Elie-M
  • 79
  • 1
  • 11