Match string to regex in javascript

I'm having problems matching a string with a regex in JS. I can use this:

/"[^"]*?"/g

      

on this line:

" this is a string "

      

but I cannot use this in this:

" this is a \"string\" "

      

how can i fix this? thank.

+3


source to share


3 answers


If I understand correctly what you want to do is check if the string is in the correct format? so there are no premature line endings?



If so, you can use /"(?:[^"\\]|\\.)*"/g

+3


source


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

      

You can try something like this. You will need to capture a group or capture and not match. See demo.

https://regex101.com/r/nS2lT4/30

or



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

      

See demo.

https://regex101.com/r/nS2lT4/31

+1


source


In this case, you shouldn't use [^"]*

, and you don't need anyone-greedy, you can use the following regex to match everything between two quotes:

/"(.*)"/g

      

Demo

And if you want to match anything in between "

, you can just use the word character match with the space helper in the character class with the global modifier:

/[\w\s]+/g

      

Demo

Alternatively, you can use negative appearance :

/(?<!\\)"(.*?)(?<!\\)"/

      

0


source







All Articles