Extract all data in between two double quotes

前端 未结 4 1070
再見小時候
再見小時候 2021-01-24 02:08

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:

相关标签:
4条回答
  • 2021-01-24 02:43

    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
                                ^
    
    0 讨论(0)
  • 2021-01-24 02:51

    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
    
    0 讨论(0)
  • 2021-01-24 03:00

    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 M.m.b.r 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.

    0 讨论(0)
  • 2021-01-24 03:02

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

    Regex101 Demo

    0 讨论(0)
提交回复
热议问题