Page 1 of 1

Delete all lines containing word1 and word2

Posted: 26 Apr 2024, 08:56
by Billykid
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!

Re: Delete all lines containing word1 and word2

Posted: 26 Apr 2024, 13:43
by ShatterCoder
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

Re: Delete all lines containing word1 and word2

Posted: 26 Apr 2024, 13:46
by mikeyww

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