Search code examples
regexautoit

Filter a string using regular expression


I tried the following code. However, the result is not what I want.

$strLine = "100.11 Q9"
$sortString = StringRegExp ($strLine,'([0-9\.]{1,7})', $STR_REGEXPARRAYMATCH)
MsgBox(0, "", $sortString[0],2)

The output shows 100.11, but I want 100.11 9. How could I display it this way using a regular expression?


Solution

  • $sPattern = "([0-9\.]+)\sQ(\d+)"
    
    $strLine = "100.11 Q9"
    $sortString = StringRegExpReplace($strLine, $sPattern, '\1 \2')
    MsgBox(0, "$sortString", $sortString, 2)
    
    $strLine = "100.11 Q9"
    $sortString = StringRegExp($strLine, $sPattern, 3); array of global matches.
    For $i1 = 0 To UBound($sortString) -1
        MsgBox(0, "$sortString[" & $i1 & "]", $sortString[$i1], 2)
    Next
    

    The pattern is to get the 2 groups being 100.11 and 9.

    The pattern will 1st match the group with any digit and dot until it reach /s which will match the space. It will then match the Q. The 2nd group matches any remaining digits.

    StringRegExpReplace replaces the whole string with 1st and 2nd groups separated with a space.

    StringRegExp get the 2 groups as 2 array elements.

    Choose 1 from the 2 types regexp above of which you prefer.