Regex to only copy a word after a specific word?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Shanghei
Posts: 28
Joined: 04 Jan 2021, 22:42

Regex to only copy a word after a specific word?

Post by Shanghei » 19 Oct 2021, 09:38

Hello all would appreciate the help on this one.

I was wondering if there was a way through regex or some other way to copy any word that follows a specific word.

So for example lets say i copy a whole sentence, and in that sentence and the word Hello (case sensitive) world comes up, it will only copy the word "world"

Would appreciate it thanks.

User avatar
Spawnova
Posts: 557
Joined: 08 Jul 2015, 00:12
Contact:

Re: Regex to only copy a word after a specific word?

Post by Spawnova » 19 Oct 2021, 10:02

There might be a more efficient way to do this but using a pretty basic regex string you can achieve this quite easily

here's an example with comments
Also consider checking out the website Regex101 for understanding regex and creating your own. =P

Code: Select all

testString =
(
Hello example ;matches example
Hello2 NotWork ;no match here
Hello two words ;matches two
Words in a sentence including Hello and hello or Hello yellow.  ;will match and/yellow
)

needleWord := "Hello" ;case sensitive,   prefixing  i)  would make it insensitive
needle := needleWord "[\s\t]+(\S+)"   ;matches Hello (any amountof spaces or tabs) (anything thats not a space+)


if (RegExMatch(testString,needle,match)) {  ;the basic function, returns just 1 match by default
	msgbox % "Found: " match1
}


matches := GetAllMatches(testString,needle) ;custom function this returns an array with all matches

str := "" ;just creating the string with all the results
for k,v in matches
	str .= (a_index = 1 ? "" : "`n") v
msgbox % "Found " matches.length() " results`n" str

exitapp


GetAllMatches(haystack,needle) {
	results := []
	
	while (p := RegExMatch(haystack,needle,match,p?p+1:1)) {
		results.push(match1)
	}
	return results
}

Rohwedder
Posts: 7680
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Regex to only copy a word after a specific word?

Post by Rohwedder » 19 Oct 2021, 10:12

Hallo,
or:

Code: Select all

ClipBoard = So for example lets say i copy a whole sentence
, and in that sentence and the word Hello world comes up
, it will only copy the word "world"
Sleep, 100
RegExMatch(ClipBoard,"Hello\W+\K\w*", M)
Sleep, 100
ClipBoard := M
Sleep, 100
MsgBox,% ClipBoard
The sleeps because Clipboard is very slow.

Post Reply

Return to “Ask for Help (v1)”