Search code examples
autohotkey

How to invert Regex match operator when using it in ternary operators?


I want to check if the initial Thiswindow variable contains AHK_ID or A, if it does NOT then assign 111 else assign 000

The below, always assigns 111 to ThisWindow, I would like it to NOT in this case, cant the operator ~= not be inverted, like so !~= or even ~!=?

ThisWindow := "Ahk_ID 0x12345"
ThisWindow := ThisWindow ~!= "Ahk_ID 0x" || ThisWindow != "A" ? "111"  : "000"
OutputDebug, %ThisWindow%

Any help would be greatly appreciated!


Solution

  • Operators are operators, you don't invert operators, but you can invert statements:
    !(ThisWindow ~= "Ahk_ID 0x")

    Though, it seems like to me that you should just reorder the logic a bit and you don't even need any unnecessary inverting etc:
    ThisWindow := (ThisWindow ~= "Ahk_ID 0x" || ThisWindow == "A") ? "000" : "111"
    And you were also missing parenthesis around the or-statement for the ternary.


    Test code:

    for each, title in StrSplit("Ahk_ID 0x12345,A,Asd", ",")
        outputs .= title ": " ((title ~= "Ahk_ID 0x" || title == "A") ? "000" : "111") "`n"
    
    MsgBox, % outputs
    

    Output:

    Ahk_ID 0x12345: 000
    A: 000
    Asd: 111