简体   繁体   中英

match a string with regexp in javascript

I have issues with matching a string with regexp in JS. I can use this:

/"[^"]*?"/g

in this string:

" this is a string "

but I can not use that in this:

" this is a \"string\" "

how can i fix that? thanks.

If i understand correct, what you want to do is test is a string is in correct format? so no premature string endings?

If that is the case you could use /"(?:[^"\\\\]|\\\\.)*"/g

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

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

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

or

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

See demo.

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

In that case you shouldn't use [^"]* also you don't need none-greedy you can use following regex for matching all between 2 quote :

/"(.*)"/g

Demo

And if you want to match anything between " you can simply use a word character matcher with white-space matcher within a character class with a global modifier :

/[\w\s]+/g

Demo

As another way you can use a negative look-behind :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM