PowerShell Tip: Extract string between string


PowerShell Tip: Extract string between string


Summary

In this TechNet Wiki article we will show a demo to extract string between two strings. Recently, we were working on Open XML and SharePoint Project and faced few issues to read the data from DOCX file. So, we used few Regex tricks to overcome the challenges.

Note

Be very sure while manipulating string using REGEX and uploading to any of the Office Servers at least. If not, please try alternate ideal approach.

Requirement

Bookmark is broken in DOCX file and we need to scrap the text to retrieve data for passing values to SharePoint metadata. Example String : ClientClientNameValue500.000EURTeamTunnelEngineeringArea1300m2Area. This string format remains same but the broken bookmark value may be in any position. Example "Area1300m2AreaClientClientNameValue500.000EURTeamTunnelEngineering".         

Solution

Windows PowerShell Regular Expression Using Windows PowerShell we can easily extract the string between two strings.

Code

$String = "Area1300m2AreaClientClientNameValue500.000EURTeamTunnelEngineering"           
$Regex = [Regex]::new("(?<=Client)(.*)(?=Value)")            
$Match = $Regex.Match($String)            
if($Match.Success)            
{            
    $Match.Value            
}

The output we get is ClientName which is between Client and Value. Enjoy PowerShell!