简体   繁体   中英

Regex select data within quotations

I have a string: "var1=\\"Some Data\\";var2=\\"More Data\\" and I would like to select the data within the quotes as well as the data to the left of it(the variable name).

For example:

"var1" = "Some Data", "var2" = "More Data"

The commands are semi-colon delimited and the variable's value is always contained within quotations. However the variables are based on user input and may also contain other quotations or semi-colons. I have attempted to do this with Split and Substring however they were affected by the user input. How would I do this without it being affected by the user input ?

Edit: I didn't think to mention that I already have an expression that selects data within the quotes. However I'm not familiar enough with Regex to make it select the variable name too. The current Regex expression is: (\\".*\\")

The Regex I decided to use was: ;(?=(?:[^\\"]*\\"[^\\"]*\\")*[^\\"]*$) . That selects the entire command ( variableName="Hello World" ) and then use Substring to select the data before and after the equals. I then use trim to remove the quotes. It works perfectly, and I am able to use quotations that are escaped within the main quotations.

I take no credit for that Regex command. I found it on the web somewhere(I will post it here when I remember where).

Thanks for all the answers and links anyway.

I believe this will do what you're after:

"(.+)"\s?=\s?"(.+)"

example: Regex Hero

Regex quantifiers + and * are greedy by default and will look for the longest match.

You can add additional test cases with more or no white space between the quoted strings and = to make sure that it will satisfy your needs.

Edit: This will not work for multiple instances on the same line, as it relies on the greediness of the quantifiers.

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