32

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

I want to get 12asdf only.

1
  • 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 8, 2010 at 16:27

4 Answers 4

95

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*"
3
  • 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 8, 2010 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 6, 2018 at 17:37
  • 1
    Like others have said, this doesn't answer the question, it gets the text WITH the quotes.
    – Hasen
    Apr 28, 2019 at 5: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.

1
  • @Don: Can you provide the link to the non-working regex (click on Save regex and post that link)? Feb 11, 2016 at 7:14
0

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

0
[^"].*[^"]

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.