简体   繁体   English

正则表达式选择报价内的数据

[英]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). 我有一个字符串: "var1=\\"Some Data\\";var2=\\"More Data\\" ,我想选择引号内的数据以及其左侧的数据(变量名)。

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. 我试图用Split和Substring来做到这一点,但是它们受到用户输入的影响。 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. 但是,我对Regex不够熟悉,无法使其也选择变量名。 The current Regex expression is: (\\".*\\") 当前的Regex表达式是: (\\".*\\")

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. 我决定使用的正则表达式是: ;(?=(?:[^\\"]*\\"[^\\"]*\\")*[^\\"]*$) 。选择整个命令( variableName="Hello World" ),然后使用Substring在等号之前和之后选择数据。然后使用trim删除引号。它工作得很好,并且我能够使用在主引号中转义的引号。

I take no credit for that Regex command. 我不相信该Regex命令。 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 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. 编辑:这对同一行上的多个实例不起作用,因为它依赖于量词的贪婪性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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