Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a substring located between 2 quotes?

I have a string that looks like this: "the word you need is 'hello' ".

What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?

Any help appreciated!

like image 539
Phil Avatar asked Sep 11 '12 09:09

Phil


People also ask

How do you find the string inside a double quote?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.

How do you string multiple quotes together?

There are two ways to do it: Use a regular string and escape the double quotes, or. Use a verbatim @"" string, and double the double quotes.

How do I extract a string between quotes in Python?

To extract strings in between the quotations we can use findall() method from re library.

How do you match double quotes in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.


1 Answers

Use match():

> var s =  "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"

This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.

like image 109
João Silva Avatar answered Oct 02 '22 13:10

João Silva