AliOzturk

Search for a string and return that string

19 posts in this topic

Hello, I want to be able to search for multiple strings and if any of the strings are found I want it returned which one it is. I've been able to search for multiple strings using the OR command, but I'm not sure how I am supposed to make it return which of my strings is found. I've given an example below

If StringInStr($html, Batman) OR  StringInStr($html, Superman) Then
   MsgBox(0, "Success", "The string found was: Superman")
EndIf

So it will search for the two strings and whichever it founds it will return me with. How can I make that work?

Share this post


Link to post
Share on other sites



I think that's a job for StringRegExp. I hope some RegExp guru will chime in to explain which pattern is needed :)


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

;~ $html = "string about Batman"
$html = "string Superman is in"

$Batman = StringInStr($html, "Batman")
$Superman = StringInStr($html, "Superman")
$sOut = $Batman > 0 ? "Batman: " & $Batman : "Superman: " & $Superman
msgbox(0, '' , $sOut)

 

This assumes there can only be one or the other, never both.

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

or make a own func for it:

$sIsIn='Batman|Superman|Spiderman'
$sString='Once a day Batman and Spiderman helped each other. As it was a hard fight against unknown enemy, they called Spiderman'
$sTest=_FindFirstMatch($sString,$sIsIn)
MsgBox(0,'func test',$sTest)
Func _FindFirstMatch($sStr, $sDelArray)
    Local $aIN = StringSplit($sDelArray,'|',3)
    For $i=0 To UBound($aIN)-1
        If StringInStr($sStr,$aIN[$i]) Then return SetError(0,$i,$aIN[$i])
    Next
    Return SetError(1,0,'')
EndFunc

 

Share this post


Link to post
Share on other sites
5 minutes ago, iamtheky said:
;~ $html = "string about Batman"
$html = "string Superman is in"

$Batman = StringInStr($html, "Batman")
$Superman = StringInStr($html, "Superman")
$sOut = $Batman > 0 ? "Batman: " & $Batman : "Superman: " & $Superman
msgbox(0, '' , $sOut)

 

This assumes there can only be one or the other, never both.

Worked like a charm thanks! Just curious, but when I am retuned with the value it is followed by a number. What is this number? 

Share this post


Link to post
Share on other sites

The string in string return, which is the position of the match.


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites
Local $stringFound = FindString ( "Superman is in" )
ConsoleWrite ( "The string found was: " & $stringFound & @CRLF )

Func FindString ( $sString )
    Local $sReturnValue = ""

        Switch $sString
            Case StringInStr ( $sString, "Superman" ) > 0
                $sReturnValue = "Superman"
            Case StringInStr ( $sString, "Batman" ) > 0
                $sReturnValue = "Batman"
        EndSwitch
        Return $sReturnValue
EndFunc

Using the switch / stringinstr statement. Assuming only one result gets returned

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

5 minutes ago, iamtheky said:

The string in string return, which is the position of the match.

Oh alright. Makes sense 

 

4 minutes ago, pluto41 said:
Local $stringFound = FindString ( "Superman is in" )
ConsoleWrite ( "The string found was: " & $stringFound & @CRLF )

Func FindString ( $sString )
    Local $sReturnValue = ""

        Switch $sString
            Case StringInStr ( $sString, "Superman" ) > 0
                $sReturnValue = "Superman"
            Case StringInStr ( $sString, "Batman" ) > 0
                $sReturnValue = "Batman"
        EndSwitch
        Return $sReturnValue
EndFunc

Using the switch / stringinstr statement. Assuming only one result gets returned

That's interesting. But what if I were to have lets say, 20 different substrings. How would I search for 20 different substrings within a string and be returned with the one that occur. (Assuming that there is only one possible of the 20).

Would I just add the other 18 to the Switch?

Edited by AliOzturk

Share this post


Link to post
Share on other sites

If we can assume that - Batman or Superman will appear in the string, and only one of them will appear.

Then its one line:

msgbox(0, '' , StringInStr($html, "Batman") ? "Batman": "Superman")

 

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

3 minutes ago, iamtheky said:

If we can assume that - Batman or Superman will appear in the string, and only one of them will appear.

Then its one line:

msgbox(0, '' , StringInStr($html, "Batman") ? "Batman": "Superman")

 

 

Haha wow. That's so much more simple, will it work with multiple strings as well? Let's say 20 different strings to search for instead of the two?

Oh wait... The problem with this is that there doesn't have to be any of them. It's a loop, so it just keeps searching until one of them appears. So this actually doesn't work with what I want, unfortunately 

Edited by AliOzturk

Share this post


Link to post
Share on other sites

see, there are rules.

$html = "string about Batman and Asterix"
;~ $html = "string about teen titans go"

local $aSuper = ["Batman" , "Superman" , "Lobo" , "Deadpool" , "Wolverine" , "Colossus" , "Sabertooth" , "Groo" , "Asterix" , "Obelix"]

$sOut = ""

For $i = 0 to ubound($aSuper) - 1
  If stringinstr($html , $aSuper[$i]) Then
     $sOut &= $aSuper[$i] & @LF
  EndIf
Next

msgbox(0, '' , $sOut = "" ? "None Found" : $sOut)

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

#include <array.au3>

; Add one or More Strings to the Array $aStringToFind
Local $aStringToFind = ["Superman", "Batman", "Captain America", "The Hulk"]
; _arraydisplay ( $aStringToFind )  ; for debugging purposes

Local $stringFound = FindString ( "Captain America is in" )
ConsoleWrite ( "The string found was: " & $stringFound & @CRLF )

; Func that loops trough the array and returns 
Func FindString ( $sString )
    For $i = 0 to UBound ( $aStringToFind ) - 1
        If StringInStr ( $sString, $aStringToFind[$i] ) > 0 Then
            Return $aStringToFind[$i]   ; String Found, return result.
        EndIf
    Next
    Return ""   ; String not found
EndFunc

Perhaps a Array is the way to go?

Edited by pluto41

Share this post


Link to post
Share on other sites

A regexp will do that nicely.

Local $s = "My friend is Superman and has a blue suit"
ConsoleWrite(_FindHero($s) & @LF)
$s = "I'm Catwoman under disguise"
ConsoleWrite(_FindHero($s) & @LF)
$s = "Written as spiDer-Man works as well"
ConsoleWrite(_FindHero($s) & @LF)
$s = "Just as Captain           AmeRiCa"
ConsoleWrite(_FindHero($s) & @LF)
$s = "But not this: Captain-AmeRiCa"
ConsoleWrite(_FindHero($s) & @LF)
$s = "Order matters: batman beats spiderman"
ConsoleWrite(_FindHero($s) & @LF)


Func _FindHero($s)
    Local $a = StringRegExp($s, "(?i)(batman|spider(?:-?)man|superman|catwoman|ironman|captain(?: +)america)", 1)
    Return (@error ? -1 : $a[0])
EndFunc

 


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

very nice, since regexp plays well with arraytostring, an array makes it all pretty like.

#include<array.au3>

$s = "string about Batman and asterix"

local $aSuper = ["Batman" , "Superman" , "Lobo" , "Deadpool" , "Wolverine" , "Colossus" , "Sabertooth" , "Groo" , "Asterix" , "Obelix"]

_ArrayDisplay(StringRegExp($s, "(?i)" & _ArrayToString($aSuper), 3))

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

My approach

$sTest = "Look, up in the sky, it's a bird, it's a plane, it's Superman"
ConsoleWrite(_FindStringInStr($sTest, "Superman"))
ConsoleWrite(@CRLF)
ConsoleWrite(_FindStringInStr($sTest, "Superman|Batman|Spiderman"))

Func _FindStringInStr($sString, $sWords)
    Local $sFind, $sReturn
    If Not StringInStr($sWords, "|") Then ; single item
        $sFind = StringInStr($sString, $sWords)
        If $sFind <> 0 Then
            Return "FOUND: " & StringMid($sString, $sFind, StringLen($sWords)) & @CRLF
        Else
            Return "NOT_FOUND: " & $sWords
        EndIf
    Else ; multiple item
        Local $aWords = StringSplit($sWords, "|", 2)
        For $i = 0 To UBound($aWords) - 1
            $sFind = StringInStr($sString, $aWords[$i])
            If $sFind <> 0 Then
                $sReturn &= "FOUND: " & StringMid($sString, $sFind, StringLen($aWords[$i])) & @CRLF
            Else
                $sReturn &= "NOT_FOUND: " & $aWords[$i] & @CRLF
            EndIf
        Next
        Return $sReturn
    EndIf
EndFunc   ;==>_FindString
FOUND: Superman

FOUND: Superman
NOT_FOUND: Batman
NOT_FOUND: Spiderman

You know what are the string found and what are not found, plus you don't need any complex regex or array


Nothing is so strong as gentleness. Nothing is so gentle as real strength

 

Share this post


Link to post
Share on other sites

And why not strictly the basics, using a func very easy to configure ?

$main_txt = "Superman is in"

Msgbox(0,"", "The found hero was: " & _FindHero($main_txt) )

Func _FindHero($sString)
    Local $sHeroes = "Batman,Superman"   ; comma-separated list of heroes

    Local $aHeroes = StringSplit($sHeroes, ",")
    For $i = 1 to $aHeroes[0]
        If StringInStr($sString, $aHeroes[$i]) Then Return $aHeroes[$i]
    Next
    Return "none"
EndFunc

 

Share this post


Link to post
Share on other sites

#17 ·  Posted (edited)

18 hours ago, mikell said:

And why not strictly the basics, using a func very easy to configure ?

$main_txt = "Superman is in"

Msgbox(0,"", "The found hero was: " & _FindHero($main_txt) )

Func _FindHero($sString)
    Local $sHeroes = "Batman,Superman"   ; comma-separated list of heroes

    Local $aHeroes = StringSplit($sHeroes, ",")
    For $i = 1 to $aHeroes[0]
        If StringInStr($sString, $aHeroes[$i]) Then Return $aHeroes[$i]
    Next
    Return "none"
EndFunc

 

Worked like a charm. Was just what I was looking for actually. Thank you!

Edited by AliOzturk

Share this post


Link to post
Share on other sites

 

18 hours ago, mikell said:

And why not strictly the basics, using a func very easy to configure ?

$main_txt = "Superman is in"

Msgbox(0,"", "The found hero was: " & _FindHero($main_txt) )

Func _FindHero($sString)
    Local $sHeroes = "Batman,Superman"   ; comma-separated list of heroes

    Local $aHeroes = StringSplit($sHeroes, ",")
    For $i = 1 to $aHeroes[0]
        If StringInStr($sString, $aHeroes[$i]) Then Return $aHeroes[$i]
    Next
    Return "none"
EndFunc

 

full ACK:

21 hours ago, AutoBert said:

or make a own func for it:

$sIsIn='Batman|Superman|Spiderman'
$sString='Once a day Batman and Spiderman helped each other. As it was a hard fight against unknown enemy, they called Spiderman'
$sTest=_FindFirstMatch($sString,$sIsIn)
MsgBox(0,'func test',$sTest)
Func _FindFirstMatch($sStr, $sDelArray)
    Local $aIN = StringSplit($sDelArray,'|',3)
    For $i=0 To UBound($aIN)-1
        If StringInStr($sStr,$aIN[$i]) Then return SetError(0,$i,$aIN[$i])
    Next
    Return SetError(1,0,'')
EndFunc

 

 

Share this post


Link to post
Share on other sites

Sorry. I began to read the thread from post #10 ...

This only means that great minds think alike   :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • LoneWolf_2106
      By LoneWolf_2106
      Hi everybody,
      i have a log file with several entries like the following one:
      INFO [26.04.2017 11:37:48] [main] XML-Data: <online-activation> <general> <userid>XYZ</userid> <mac-address/> <OU>VG-DE</OU> <ROLE>KDT</ROLE> <FOA>PRO;FC;DOM;MDD</FOA> <BRD>XYZ;IMP</BRD> </general> <applications> <app expiration-date="2017-10-01" name="BB-INFO"/> <app expiration-date="2017-10-01" name="MMSKD"/> <app expiration-date="2017-10-01" name="FM-TOOL"/> <app expiration-date="2017-04-05" name="WEB-BTD"/> <app expiration-date="2017-10-01" name="OFFLINE-BTD"/> <app expiration-date="2017-10-01" name="MDU-UPD"/> <app expiration-date="2017-10-01" name="MDU"/> <app expiration-date="2017-04-05" name="WEB-WDA"/> <app expiration-date="2017-04-05" name="WEB-ETD"/> <app expiration-date="2017-10-01" name="OFFLINE-WDA"/> <app expiration-date="2017-10-01" name="OFFLINE-ETD"/> </applications> </online-activation>  
      I need to collect all the XML-Data, my search doesn't work:
       
      Func FileSearch() $j=0 For $i = 0 To UBound($content_array) - 1 $search_result=StringInStr($content_array[$i],$search) If $search_result<>0 Then ReDim $searchResultArray[UBound($searchResultArray) + 1] $searchResultArray [$j] = $content_array[$i] _ArrayDisplay($searchResultArray) $j+=1 EndIf Next EndFunc If i search for "online-activation", it retrieves only the first and the last tag, but not what is within.
      In addition, when i use FileReadToArray, all the entries between <online-activation> and </online-activation>

    • MrSparty1995
      By MrSparty1995
      I have a good handle on how to read a file line by line, and search for a given string.
      Basically using, FileOpen, FileReadLine, and StringInStr.
      I have been trying to figure out why my search keeps coming back with no match.
      For example, if my string line was "Where is Waldy", and I was searching for Waldy that comes back fine.
      But in my file, Let's say it is
      Where is "Waldy"
      So i read that line in and do a search for Waldy, but i comes back with no match since there is quotes around it.
      Is there a way to resolve this?
      Here is my actual example
      The line comes back like this
          <JposEntry logicalName="LineDisp_iSC480">
      I'm searching for LineDisp_iSC480, but its coming back with no match due to the quotes.
      Thanks in advance, James
    • rootx
      By rootx
      #include <Array.au3> #include <File.au3> #include <MsgBoxConstants.au3> Local $path="C:\Users\rootx\Desktop\Nuova cartella",$mask = "*.jpg;*.png;*.ico",$Pos $FileArr = _FileListToArrayRec($path,$mask,1,1,1,2) For $x = 1 to UBound($FileArr)-1 If $Pos = StringInStr($FileArr[$x],"-") Then ConsoleWrite("------"&$FileArr[$x]&@CRLF) Else ConsoleWrite($FileArr[$x]&@CRLF) FileDelete($FileArr[$x]) EndIf ConsoleWrite($x&@CRLF) Next ConsoleWrite($x-1&@CRLF) I would write a loop that individuals and delete files that contain this feature....
      File name-150x100.jpg, or other -SizexSize
      But in this case how can I filter properly?
      File name 150x100-150x100.jpg
      File name -100-150x100.jpg
       
    • Italiano
      By Italiano
      Hello,
      As always, sorry for my bad english.
      here is the code i have
      #include <File.au3> #include <String.au3> $file1 = "d:\doppioniautoit\international.txt" FileOpen($file1, 0) $file2 = "d:\doppioniautoit\standard.txt" FileOpen($file2, 0) For $i = 1 to _FileCountLines($file1) $line = FileReadLine($file1, $i) $aExtract = _StringBetween($line, "(", ")") ;MsgBox(0, $line, $aExtract[0]) $itime = TimerInit() For $x = 1 to _FileCountLines($file2) $line2 = FileReadLine($file2, $x) Local $iPosition = StringInStr($line2, $aExtract[0], 1) ;Local $iPosition = StringRegExp($line2,$aExtract[0], 0) if $iPosition <> 0 then ;MsgBox(0, "Trovato", $aExtract & " " & $line2) endif ConsoleWrite($line2 & @CRLF) Next ConsoleWrite(@TAB&'Str='&TimerDiff($itime)&' ms'&@lf) MsgBox(0, "TIME", @TAB&'Str='&TimerDiff($itime)&' ms'&@lf) Next FileClose($file1) So, what do i want to do? I try to explain with my poor english   Basically, i have 2 text files (see attachments below). They both contains movie titles with Director and Year  in this form
      Movie Title (Director, Year)
      "Standard.txt" contains, mostly, italian titles. "International.txt", as you can image, contains the internationals one. With the script i would like to search for the Director, Year of "international.txt" in the "standard.txt" file.
      For example... first row of "international.txt" is "¡Atraco! (Cortés, 2012)". The script takes just the "Cortés, 2012" and it searches for it in the standard. txt file.
      The simple code i wrote works...  I tried using StringInStr and using StringRegExp.. they both need about 2 minutes and 30 seconds (stringinstr is little faster) to process one row.
      I was wondering... is there any other method to make it faster using autoit? Any help would be much appreciated, thx!
       
       
      standard.txt
      international.txt
    • souldjer777
      By souldjer777
      Good Morning All,
      I'm hoping someone here can work their AutoIT magic 
      I'm doing a pretty "simple" string search in a HUGE variable.
      But I'm doing the basics almost straight out of the Help File...

      ( sorry, I'm leaving out my main code for privacy reasons )
      Local $hFileOpen = FileOpen($sFilePath, $FO_READ) Local $sFileRead = FileRead($hFileOpen) Local $sEmailPosition01 = StringInStr ($sFileRead, $sEmailAddress ) Everything looks good with my troubleshooting
      I ran IsString against $sFileRead and $sEmailAddress and was okay: "The variable is a string"
      So then I ran StringLen($sFileRead) and got string length 68352786
      Yeah, I know... That's HUGE - But it worked with the older version of AutoIT (upgraded yesterday) v3.3.14.2
      Is there an "Excessive" variable I should set?!? lol. Should I search the string a different way maybe?
      I know the string is in there... but I'm getting a StringInStr @error : 0 @extended: 0
      Please help! Thank you all