Jump to content
CaptainSparky

StringLeft help!

Recommended Posts

CaptainSparky

Hello good friends of Autoit, so I am making a chatbot using Autoit but I got stuck on this part:

I already have stringright($var,stringlen($var) - stringlen(" = ") - StringInStr($var," = ") + 1) the program is made to read a text file and extract from a specific line the text after = and before =, for example:

example line of text file: something = okay this is a text

and I needed to extract the right part (which I already have done) and the left part (which I need help with) so how can you make stringleft to get all text before "="?

Thanks in advance.

Here's my code if you need it:

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <File.au3>
#include <Misc.au3>
#Include <Array.au3>

Global $BrainLocation = @ScriptDir & "\brain.txt"
Global $FormName = "Project Lisa"
Global $ReatInput = "null"
Global $Memory[100]
Global $BrainLineCount = 1
Global $Random[100]
Global $RandomCount = 0
Global $SplitInput[100]
Global $BrainCount = 0

Loader()

Func Loader()

    Global $Form = GUICreate($FormName, 417, 279, 192, 124)
    Global $Output = GUICtrlCreateEdit("", 8, 8, 401, 225, BitOR($ES_AUTOVSCROLL,$ES_AUTOHSCROLL,$ES_WANTRETURN,$WS_HSCROLL),0)
    Global $Input = GUICtrlCreateInput("", 104, 240, 209, 21)
    GUISetState(@SW_SHOW)
    ControlFocus($FormName,"",$input)
    HotKeySet("{ENTER}","SendText")

    Main()

EndFunc

func Main()

    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                Exit
        EndSwitch
    WEnd

EndFunc


Func SendText()

    $ReatInput = GUICtrlRead($Input)
    GUICtrlSetData($Output,@CRLF & "You > " & $ReatInput,1)

    CreateRandoms()

EndFunc

Func CreateRandoms()

    While $RandomCount <> 100
        $Random[$RandomCount] = Random(1,$RandomCount,1)
        $RandomCount += 1
    WEnd
    $RandomCount = 0

    BrainLoader()

EndFunc

Func BrainLoader()

    $ReatBrain = FileReadLine($Brainlocation,$BrainLineCount)
    $BrainStringRight = stringright($ReatBrain,stringlen($ReatBrain) - stringlen(" = ") - StringInStr($ReatBrain," = ") + 1)
    MsgBox(0,"",$Brainstringright)
    $BrainStringLenRight = Stringlen($brainstringright)
    MsgBox(0,"",$Brainstringright)
    $BrainActualString = 0 + $BrainStringLenRight - 10
    MsgBox(0,"",$BrainActualString)
    $test = StringLeft($ReatBrain,$brainactualstring)
    MsgBox(0,"",$test)
    $BrainSplitedStrings = StringSplit($BrainStringRight,",")

    If $BrainSplitedStrings[1] <> "" Then
        $_1 = "true"
        $BrainCount += 1
    EndIf

    If $ReatInput = $BrainActualString Then
        $BrainRan = Random(1,$braincount)
        GUICtrlSetData($output,@CRLF & "Lisa > " & $BrainSplitedStrings[$BrainRan],1)
        $BrainLineCount = 1
        Main()
    Else
        main()
    EndIf
    $BrainLineCount += 1
    BrainLoader()

EndFunc

Hello.

If in someway I have helped, please consider liking my post(s).

The formula for the right answer: You + Right Question = Answer

(Think) BEFORE you post.

Share this post


Link to post
Share on other sites
javiwhite

if you need both parts of the text, why don't you just use stringsplit?

$text = "some = text"
$Split = StringSplit($text,"=")
ConsoleWrite($Split[1]) ;Some
ConsoleWrite(@CR)
ConsoleWrite($Split[2]) ;Text

Many Thanks

Javi

  • Like 1

give a man an application, and he'll be frustrated for the day, Teach him how to program applications and he'll be frustrated for a lifetime.

Share this post


Link to post
Share on other sites
CaptainSparky

Holy cow! HOW DID I DIDN'T THINK OF THAT? how stupid of me. Thank you good friend.


Hello.

If in someway I have helped, please consider liking my post(s).

The formula for the right answer: You + Right Question = Answer

(Think) BEFORE you post.

Share this post


Link to post
Share on other sites
Skysnake

Also look at the Regular Expressions?


Skysnake

Why is the snake in the sky?

Share this post


Link to post
Share on other sites
TheDcoder

You might wanna look at my StringTrimRightUntil & StringTrimLeftUntil functions here

They are more efficient & simple! TD :D


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites
CaptainSparky

Thank you guys.


Hello.

If in someway I have helped, please consider liking my post(s).

The formula for the right answer: You + Right Question = Answer

(Think) BEFORE you post.

Share this post


Link to post
Share on other sites
CaptainSparky

Sorry that didn't work out... I need the opposite ( the left version ) of this one : stringright($var,stringlen($var) - stringlen(" = ") - StringInStr($var," = ") + 1)

I need to stringleft after/before a specific character(s) for example in the one above is after =, the one I need should be Get all text BEFORE =.

anyone? thanks in advance :)

Edited by TheNewHunter

Hello.

If in someway I have helped, please consider liking my post(s).

The formula for the right answer: You + Right Question = Answer

(Think) BEFORE you post.

Share this post


Link to post
Share on other sites
CaptainSparky

Okay I got it guys.


Hello.

If in someway I have helped, please consider liking my post(s).

The formula for the right answer: You + Right Question = Answer

(Think) BEFORE you post.

Share this post


Link to post
Share on other sites
javiwhite

StringSplit all the way my friend, Even if it's just for ease of reading when you come back to a code a few months later (it's amazing how a solution to a problem you face can seem innovative at the time, But then Jargon when you come back to the code.) Even if you're just looking for the left part of the string, StringSplit can accomplish this:

$text = "some = text"
$Left = StringSplit($text,"=")[1] ;Notice the array number
$Right = StringSplit($text,"=")[2] ;These run the stringsplit command, And then return that element to the variable from the resulting array
Consolewrite($Left)
ConsoleWrite(@CR)
ConsoleWrite($Right)

Just a handy little trick I discovered after a while of using AutoIt, The same applies to any commands that return arrays.

Cheers

Javi

  • Like 1

give a man an application, and he'll be frustrated for the day, Teach him how to program applications and he'll be frustrated for a lifetime.

Share this post


Link to post
Share on other sites
MikahS

@TheNewHunter Make sure you post your solution, so that anyone that has the same problem can see how you solved it. ;)

  • Like 1

Snips & Scripts


My Snips: graphCPUTemp ~ getENVvars
My Scripts: Short-Order Encrypter - message and file encryption V1.6.1 ~ AuPad - Notepad written entirely in AutoIt V1.9.4

Feel free to use any of my code for your own use.                                                                                                                                                           Forum FAQ

 

Share this post


Link to post
Share on other sites
Malkey

Also look at the Regular Expressions?

Using a regular expression allows control over optional spaces before and after the equal sign, and having those spaces (if they exist) not appearing in the required 'before and after' text.

$text = "some = text"

; These StringRegExpReplace replaces all text matched with nothing, "".   (Match the characters to be deleted)

$Left = StringRegExpReplace($text, "\h*=.*$", "")
; "\h*"  Match all spaces (if they exist) immediately before "=".   Note:- A space is a character, and can be classified as a horizontal whitespace character.
; "="    Match the equal character.
; ".*$"  Match all characters (if any exist) to the end of the test string (from immediately after "=").

$Right = StringRegExpReplace($text, "^.*=\h*", "")
; "^.*"  Match all characters (if any exist) from the beginning of the test string to immediately before "=".
; "="    Match the equal character.
; "\h*"  Match all spaces (if they exist) immediately after "=".
; See AutoIt help file under StringRegExp for regular expression syntax.

ConsoleWrite("Left:  " & $Left & @LF)
ConsoleWrite("Right: " & $Right & @LF)


@javiwhite
Another handy little trick, if you are writing your scripts in SciTE, is to type in lower case "cw ".  That is, type"cw" followed by a space. This is the SciTE4AutoIt3 abbreviation for "ConsoleWrite(| & @LF) ".  I use it often.  
The complete list of SciTe-AutoIt abbreviations can be found in the SciTe help file > under the "Index" tab  > SciTE4AutoIt3-AbbreviationList.
 

  • Like 2

Share this post


Link to post
Share on other sites
iamtheky

Just a handy little trick I discovered after a while of using AutoIt, The same applies to any commands that return arrays.

You have no validation that stringsplit succeeded and risk throwing an exception attempting to access an element that does not exist, so you may want to do a stringinstr to verify an equals sign is present prior to running that.  or just split it once and check for an error then access the elements.


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

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

    • VollachR
      By VollachR
      Hi,
      I'm looking for a way to take a number value from a Row2 of a 2D array and according to this check if files that appear in rows 3-11 in the array exists.
      For example, if the number in Row2 is 5 I need to check for the files in Row 3-6 only, if it is 6 than rows 3-7 and so on.
      I thought on using a FOR loop but I have very little experience with those.
      Can you suggest the best way to do what I need?
      BTW, the files in Rows 3-11 will usually have blank value for any row above the number in Row2 (e.g. Row2 = 5 so Rows3-6 will have values but 8-11 be empty), The values I need are in Column 1 of the array, the name of the key from the INI file that the array was created from is in Column 0.
      Full Example:
      Row2 of Array:
      Col0 = Games# - Col1 = 5
      Rows3-6
      Col0 = Exe2 - Col1 = Path To File
      Col0 = Exe3 - Col1 = Path To File
      Col0 = Exe4 - Col1 = Path To File
      Col0 = Exe5 - Col1 = Path To File
      I need that if Row2 is 5 to check these above for rows if the file exists, if it was 6 then the next row as well and so on up until number 10 in Row2 as it can't go above 10.
      So basically for whatever number in Row2 from 2-10 need to check 1-9 rows from 3-11 to see if the files in Col1 exists and if any of them don't exist it should call a function that shows an error message.
      I'm pretty sure I have the first line of the for look correct:
      For $i = 1 To $aAIO[2][1] Just not sure how to continue from there, also not sure if $i should be equal 1 or 2.
      Help will be appreciated.
    • VollachR
      By VollachR
      Hi,
      I've written a specialty INI file editor for a specific set of INI files related to a bigger script I'm working on.
      I'm trying to create a verification script that checks the ini files structure and format and gives an error if they are not in expected format.
      What I did so far is create a couple of custom arrays, each with the list of Sections expected in the files and I use IniReadSectionNames in order to read the sections from the selected INI file and compare it to the array.
      It works fine, excepts it only gives an error if one or more of the sections in the custom array is missing, if they all exist but there are other additional sections that shouldn't be there it doesn't give an error and continue to open the editor screen.
      Here are the relevant part of my script:
      The Custom Verification Arrays:
      ;Creating Arrays for INI Verification Global $aSettingsVerify[7] $aSettingsVerify[1] = "Conversion" $aSettingsVerify[2] = "AIO" $aSettingsVerify[3] = "Data" $aSettingsVerify[4] = "Redist" $aSettingsVerify[5] = "Split" $aSettingsVerify[6] = "Autorun" Global $aDataVerify[6] $aDataVerify[1] = "Compression" $aDataVerify[2] = "Exclude" $aDataVerify[3] = "LangExclude" $aDataVerify[4] = "PreCommands" $aDataVerify[5] = "PostCommands" The IniReadSectionNames verification part:
      Case $OK If StringInStr($ActiveConfig, "Settings.ini") Then $CheckArray1 = IniReadSectionNames($ActiveConfig) $CheckArray2 = _ArrayCompare($aSettingsVerify, $CheckArray1) $CheckArray3 = UBound($CheckArray2, 1) If $CheckArray3 = 1 Then GUIDelete($ConfigStart) SettingsGUI() EndIf If $CheckArray3 > 1 Then WrongIni() EndIf EndIf If StringInStr($ActiveConfig, "Data") Then $CheckArray1 = IniReadSectionNames($ActiveConfig) $CheckArray2 = _ArrayCompare($aDataVerify, $CheckArray1) $CheckArray3 = UBound($CheckArray2, 1) If $CheckArray3 = 1 Then GUIDelete($ConfigStart) DataGUI() EndIf If $CheckArray3 > 1 Then WrongIni() EndIf EndIf The Function that performs the compare: (Found it in another thread on this forums somewhere by using Google Search)
      ;Compares Imported INI file with the Verification array Func _ArrayCompare(ByRef $a1, ByRef $a2) Local $nOldSize = UBound($a2) Local $a3[$nOldSize], $nNewSize = $nOldSize For $i = 0 To UBound($a1) - 1 For $j = 0 To $nOldSize - 1 If Not $a3[$j] And ($a1[$i] = $a2[$j]) Then $a3[$j] = 1 $nNewSize -= 1 EndIf Next Next Local $a4[$nNewSize], $j = 0 For $i = 0 To $nOldSize - 1 If Not $a3[$i] Then $a4[$j] = $a2[$i] $j += 1 EndIf Next Return $a4 EndFunc ;==>_ArrayCompare  
      Any way to make a check if there are sections other than the ones in the Verification Array and produce an error?
      Thanks
    • VollachR
      By VollachR
      Hi,
      I'm using _FileListToArray to create an array listing .ini files in a specific folder, problem is, I want only the file named Settings.ini and any Files named Data#.ini where # is actually a number, I don't want any other .ini file that may be there even though it shouldn't be there to be included in the array.
      Is it possible to use multiple filters in _FileListToArray? or is there another way to do what I'm looking for?
      My current code:
      $IniList = _FileListToArray(@ScriptDir & "\Settings", "*.ini", 1, False) _ArraySort($IniList, 1, 1) _ArraySort($IniList, 0, 2) $IniOptions = _ArrayToString($IniList, "|", 1)  
      Thank you.
    • VollachR
      By VollachR
      Hi,
      I'm creating a tool to edit some ini files that belong to a program I'm working on...
      Basically everything work fine except I can't find a way to check if the if the WriteIniSection operation was successful...
      For Example, let's say the INI file is by mistake or some other reason Read Only, or the user don't have the right permission to write to the file or the folder it's in... Right now, in such a case The INI file, as expected, won't get updated, but I when I perform an if error or if not error checks I always get the msgbox for the if not error.
      Here's the relevant code part:
       
      IniWriteSection(@ScriptDir & "\Settings\Settings.ini", "Conversion", $aConversion, 1) IniWriteSection(@ScriptDir & "\Settings\Settings.ini", "AIO", $aAIO, 1) IniWriteSection(@ScriptDir & "\Settings\Settings.ini", "Data", $aData, 1) IniWriteSection(@ScriptDir & "\Settings\Settings.ini", "Redist", $aRedist, 1) IniWriteSection(@ScriptDir & "\Settings\Settings.ini", "Split", $aSplit, 1) IniWriteSection(@ScriptDir & "\Settings\Settings.ini", "Autorun", $aAutorun, 1) If Not @error Then MsgBox($MB_ICONINFORMATION, "Success", "Settings.ini Saved Successfully") Else If @error Then MsgBox($MB_ICONERROR, "Failure", "Settings.ini Could Not Be Saved!" & @CRLF & @CRLF & "Please Check If The File Is ReadOnly And That You Have Permission To Change It Or Its Location") EndIf EndIf  
      How can I perform a check to see if the ini file was written to successfully?
      Thanks.
    • VollachR
      By VollachR
      Hi,
      I'd like to show a progress bar for an operation performed by an external program my script is running silently, I want to show it in a GUI I created using the GUICtrlCreateProgress but I have no idea how to do it.
      The important thing to point out is that there's no way of knowing how long the external program will run, as it is a file splitter and it depends on the size of file it splits and the split parts size.
      Can someone point me in the right direction or give me an example how to do so?
      This is my RunWait command:
      RunWait($MYFILES1 & '\fsplit.exe -split ' & $Size & ' mb ' & $File & " -f " & $File & "." & $extension) It uses multiple variables declared and set earlier in the script, how will I got about having the progress of that command shown using GUICtrlCreateProgress ? Is it possible?
      Thank you.
×