Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex find characters between " "

Tags:

regex

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

I want to get 12asdf only.

like image 917
dave Avatar asked Mar 08 '10 16:03

dave


People also ask

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

How do you use wildcards in regex?

In regular expressions, the period ( . , also called "dot") is the wildcard pattern which matches any single character. Combined with the asterisk operator . * it will match any number of any characters.


2 Answers

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*" 
like image 151
codaddict Avatar answered Sep 23 '22 08:09

codaddict


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.

like image 39
Tim Pietzcker Avatar answered Sep 21 '22 08:09

Tim Pietzcker