简体   繁体   中英

Extract all data in between two double quotes

I'm trying to use a powershell regex to pull version data from the AssemblyInfo.cs file. The regex below is my best attempt, however it only pulls the string [assembly: AssemblyVersion(" . I've put this regex into a couple web regex testers and it LOOKS like it's doing what I want, however this is my first crack at using a powershell regex so I could be looking at it wrong.

$s = '[assembly: AssemblyVersion("1.0.0.0")]'
$prog = [regex]::match($s, '([^"]+)"').Groups[1].Value

You also need to include the starting double quotes otherwise it would start capturing from the start until the first " is reached.

$prog = [regex]::match($s, '"([^"]+)"').Groups[1].Value
                            ^

Try this regex "([^"]+)"

Regex101 Demo

Regular expressions can get hard to read, so best practice is to make them as simple as they can be while still solving all possible cases you might see. You are trying to retrieve the only numerical sequence in the entire string, so we should look for that and bypass using groups.

$s = '[assembly: AssemblyVersion("1.0.0.0")]'
$prog = [regex]::match($s, '[\d\.]+').Value

$prog

1.0.0.0

For the generic solution of data between double quotes, the other answers are great. If I were parsing AssemblyInfo.cs for the version string however, I would be more explicit.

$versionString = [regex]::match($s, 'AssemblyVersion.*([0-9].[0-9].[0-9].[0-9])').Groups[1].Value
$version = [version]$versionString

$versionString

1.0.0.0

$version

Major  Minor  Build  Revision
-----  -----  -----  --------
1      0      0      0    

Update/Edit:

Related to parsing the version (again, if this is not a generic question about parsing text between double quotes) is that I would not actually have a version in the format of Mmbr in my file because I have always found that Major.minor are enough, and by using a format like 1.2.* gives you some extra information without any effort.

See Compile date and time and Can I generate the compile date in my C# code to determine the expiry for a demo version? .

When using a * for the third and fourth part of the assembly version, then these two parts are set automatically at compile time to the following values:

third part is the number of days since 2000-01-01

fourth part is the number of seconds since midnight divided by two (although some MSDN pages say it is a random number)

Something to think about I guess in the larger picture of versions, requiring 1.2.*, allowing 1.2, or 1.2.3, or only accepting 1.2.3.4, etc.

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