Delete all lines containing word1 and word2

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Billykid
Posts: 98
Joined: 16 Sep 2019, 08:59

Delete all lines containing word1 and word2

26 Apr 2024, 08:56

What is the code for RegExReplace that deletes all lines containing both word 1 and word 2 and does the same as the code below?

How can I replace this code with a RegExReplace expression?

Code: Select all

Text := "
(
Here is a line with a lot of text.
Here is a line with the word often used.
This line has little content.
Another line with often and much.
One further line without matching words.
Example line with often and much.
)"


Word1 := "often"
Word2 := "much"

; Split the text into lines
Lines := StrSplit(Text, "`n")

; Iterate through each line
NewText := ""
Loop, % Lines.MaxIndex()
{
    Line := Lines[A_Index]

    ; Check if the line contains both word1 and word2
    if !(InStr(Line, Word1) && InStr(Line, Word2))
    {
        ; Add the line to the new text if both words are not present
        NewText .= Line "`n"
    }
}

; Output the result
MsgBox % NewText

A big thank for your help in advance!
ShatterCoder
Posts: 84
Joined: 06 Oct 2016, 15:57

Re: Delete all lines containing word1 and word2

26 Apr 2024, 13:43

I needed help on this one myself, My initial try failed even though I was able to make it work just fine on regex101.com so this answer is not actually from me it's from user 'andreas@esa:~€ sudo -i' on discord... that being said here ya go:

Code: Select all

Text :=
(
"Here is a line with a lot of text.
Here is a line with the word often used.
This line has little content.
Another line with often and much.
One further line without matching words.
Example line with often and much.
And I can do this as often as I want to.
See? Not much to dislike here..."
)
Word1 := "often"
Word2 := "much"
NewText := RegExReplace(Text, "[^\r\n]*\b((" word1 ")|(" word2 "))\b[^\r\n]*\b((?(2)(?3)|(?2)))\b[^\r\n]*[\r\n]*")
MsgBox % NewText
for anyone wondering why my first attempt failed it was some strange reliance on CR's vs NL's
User avatar
mikeyww
Posts: 27136
Joined: 09 Sep 2014, 18:38

Re: Delete all lines containing word1 and word2

26 Apr 2024, 13:46

Code: Select all

#Requires AutoHotkey v1.1.33.11
txt := "
(
Here is a line with a lot of text.
Here is a line with the word often used.
This line has little content.
Another line with often and much.
One further line without matching words.
Example line with often and much.
)"
word1 := "often"
word2 := "much"
b     := "\b.*\b"
regex := "m`ai)^.*\b(" word1 b word2 "|" word2 b word1 ")\b.*$\R?"
txt   := Trim(RegExReplace(txt, regex), " `t`r`n")
MsgBox 64, Result, % txt

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: DevWithCoffee, gapk, sofista and 130 guests