Jump to content
Sign in to follow this  
rkr

To read a line based on string search from a text file

Recommended Posts

Hi, i want to read a particular string from a text file using autoit. i wish to read it without explicitly opening the text file. the copied string should be then transferred to an excelbook (again, no need to explicitly open the excel book)... 

with reference to my screenshot attached, my input to the  'script'' is going to be 0017-0008, and the script should copy the highlighted two lines from the input file to excel

thanks

input.png

Share this post


Link to post
Share on other sites

@rkr Good morning, and welcome to the AutoIt forum :)
The best thing I should do is read the content of the file, and then parse it in order to find what you were looking for.
Then, if you match something, you can take the line/lines matched, and paste in a new file.
In the help, look for File* and _File* functions, to have an idea of what they do :)

Feel free to ask if you need any help!

Francesco

Edited by FrancescoDiMuro

Click here to see my signature:

Spoiler

Thoughts:

  • I will always thank you for the time you spent for me.
    I'm here to ask, and from your response, I'd like to learn.
    By my knowledge, I can help someone else, and "that someone" could help in turn another, and so on.

/*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

ALWAYS GOOD TO READ:

 

Share this post


Link to post
Share on other sites

@rkr , We can help you if you can provide textfile to parsed and a sample code that we can start with.

To give hint of what FrancescoDiMuro means is this "Local $aSection = IniReadSectionNames(@ScriptDir & "\test.txt")" or "Local $var = IniReadSection(@ScriptDir & "\Testing.txt", $sValue)" and then go for "For $i = 1 To $var[0][0]... Next" to get the array from IniReadSection(). With that maybe you can start checking our help file.

You can start with this.

Local $sValue = InputBox("Testing", "Value to search...", "") ;value to search in text file
Local $var = IniReadSection(@ScriptDir & "\Testing.txt", $sValue)
If @error Then
    MsgBox(4096, "", "Error occurred, probably no INI/TEXT file.")
Else
    For $i = 1 To $var[0][0]
        MsgBox(4096, "", "Key: " & $var[$i][0] & @CRLF & "Value: " & $var[$i][1]) ;display the array
    Next
EndIf

in Text file data is:

[0017-0008]
0017
0008

Or

#include <Array.au3>

Local $readvalue, $aSection = IniReadSectionNames(@ScriptDir & "\test.text")

For $i = 1 To UBound($aSection) - 1
    $readvalue = IniReadSection("test.ini", $aSection[$i])
    If $readvalue[0][0] = 1 And $readvalue[1][0] = "name" And $readvalue[1][1] = "askjfjgkjfd" Then ; input to search in text file, you can also change this to InputBox().
        MsgBox(0, 'Section name is', $aSection[$i]); check if input is correct
        _ArrayDisplay($readvalue, "read"); display the array from $readvalue
    EndIf
Next

in Text file data is:

[123456]
name = asdasdasd
[564665]
name = asdmfkggf
[465468]
name = askjfjgkjfd

Else, let us know further for your needs.

 

KS15


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites


 @KickStarter15, thanks for that detail help.. i tried the code, but i am getting error message - but the file is in the same location  - tried _filecountlines and it worked perfectly - which means the error is not due to lack of access. i am attaching the text file (gaplst.) and the script with this. could you please have a look.. thanks

copychunk.au3

gaplst

Share this post


Link to post
Share on other sites

@rkr,

Try this and try playing with it.^_^

#include <File.au3>

Dim $array

$file = @ScriptDir & "\gaplst.txt"
$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Lines that match will be shown.', 'Text To Match', '', 200, 140)
$found = 0
$lines = ''

If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($array[$i], $find) Then
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
        EndIf
    Next
    MsgBox(64, 'Done', 'Total lines found = ' & $found & @CRLF & _
            'Searched Line(s)= ' & FileReadLine($file, $lines))
    $sFile = @ScriptDir & '\New.txt'
    $hFile = FileOpen($sFile, $FO_APPEND)
    FileWrite($hFile, FileReadLine($file, $lines)) ; to see if the line is correct
    FileClose($hFile)
Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

Also, as noticed with your text file, member name is not unique it is repeatedly occurring in the text file, so better to search the unique member name to show your input.

Example:

You want yo search for 0017-0008... then it should as this "0017-0008 0017 L2A" to show the data you wanted. I'll check on this later that it can only show the data you wanted but for now, you can play with it.;)

 

 

KS15

Edited by KickStarter15

Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites
On 1/19/2018 at 7:21 AM, KickStarter15 said:

@rkr,

Try this and try playing with it.^_^

#include <File.au3>

Dim $array

$file = @ScriptDir & "\gaplst.txt"
$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Lines that match will be shown.', 'Text To Match', '', 200, 140)
$found = 0
$lines = ''

If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($array[$i], $find) Then
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
        EndIf
    Next
    MsgBox(64, 'Done', 'Total lines found = ' & $found & @CRLF & _
            'Searched Line(s)= ' & FileReadLine($file, $lines))
    $sFile = @ScriptDir & '\New.txt'
    $hFile = FileOpen($sFile, $FO_APPEND)
    FileWrite($hFile, FileReadLine($file, $lines)) ; to see if the line is correct
    FileClose($hFile)
Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

Also, as noticed with your text file, member name is not unique it is repeatedly occurring in the text file, so better to search the unique member name to show your input.

Example:

You want yo search for 0017-0008... then it should as this "0017-0008 0017 L2A" to show the data you wanted. I'll check on this later that it can only show the data you wanted but for now, you can play with it.;)

 

 

KS15

thanks a lot KS15, that was to the point..helped me

Share this post


Link to post
Share on other sites
On 1/21/2018 at 2:23 PM, rkr said:

thanks a lot KS15, that was to the point..helped me

I want to help you but not much that I can do with your application. Maybe there are other coder here that knows how to deal with this.

As for the head start, you can check my code below. Note: Member name is unique and as you've noticed, I added letter 'a' in member number '0017-0008a' to see if the code worked (attached). Take a test on this:

First code is to loop thru your text file and find all the occurrences of the searched number.

#include <File.au3>

Dim $array, $sLine

$file = @ScriptDir & "\gaplst.txt"
$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Member Number:', 'Text To Match', '', 200, 140)
$found = 0
$lines = ''

If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($sLine, $find) And Not $iValid Then
            $iValid = 1
            ContinueLoop
        EndIf
        If StringInStr($array[$i], $find) Then
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
            $sLine = MsgBox(4, 'Done', 'Total lines found = ' & $found & @CRLF & _
                  'Searched Line(s)= ' & FileReadLine($file, $i) & @CRLF & @CRLF & _
                  'Proceed searching.')
            $sFile = @ScriptDir & '\New.txt'
            $hFile = FileOpen($sFile, $FO_APPEND)
            $sLine = FileReadLine($hFile)
            FileWrite($hFile, FileReadLine($file, $i) & @CRLF)
            FileClose($hFile)
         ElseIf $sLine = 7 Then
           Exit
        EndIf
    Next
   Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

 

The next code is to get what you need to be searched but again it needs to be unique like letter "a" was added in the searched number. ConsoleWrite() will show you the results.:sweating:

#include <File.au3>
#include <Array.au3>

Dim $array

$find = InputBox('What To Find', 'Type in below what to search for.' & @CRLF & _
        'Member Number:', 'Text To Match', '', 200, 140)

Global $file = @ScriptDir & "\Testing.txt", $find
Global $iLine = 1, $sLine = '', $iValid = 0
Global $hFile = FileOpen($file)

$found = 0
$lines = ''

If $hFile = -1 Then
    MsgBox(0,'ERROR','Unable to open file for reading.')
    Exit 1
EndIf
If $file <> '' And $find <> '' Then
    _FileReadToArray($file, $array)
    For $i = 1 To UBound($array) - 1
        If StringInStr($array[$i], $find) Then
            Global $iLine = 0, $sLine = '', $iValid = 0
            $array[$i] = ''
            $found += 1
            $lines &= $i & ', '
            ConsoleWrite(FileReadLine($file, $i) & @CRLF)
        EndIf
    Next
   Else
    MsgBox(48, 'Error', 'A file was not picked or what to find was cancelled/empty!')
EndIf

; do a loop to locate the next line of $find
While 1
    $iLine += 1
    $sLine = FileReadLine($hFile)
    If @error = -1 Then ExitLoop

    ; test the line for the $search string until the flag $iValid is set
    If StringInStr($sLine, $find) And Not $iValid Then
        $iValid = 1
        ContinueLoop
    EndIf

    If $iValid Then
        $iValid += 1
        ConsoleWrite($sLine & @CRLF) ; To check if the search lines are correct. NOTE: It should be unique, else I have nothing to do.
        If $iValid > 5 Then ExitLoop
    EndIf
WEnd
FileClose($hFile)

Hope you can get an idea with these codes.^_^

 

Code2 text file.PNG


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites

thanks for all that KS15, just one more doubt.. i stored the following line into an array

0017-0008  0017  l2a  1  -18407.00    5110.90    0.00    0.03    -70735.59

 

i was trying stringsplit to store each of them above as a vairable

ie; $string1 should be 0017-0008,

$string2 =0017,

$string3=l2a,

 $string4=1

$string5=-18407.00 and so on till $string9

 

how do i achieve this as the delimitter in this case is not a constant... in all cases, there will be 'space' between the strings/numbers, however, the number of spaces change depending on the number, sign of number etc.. 

 

thanks for all the help

 

Share this post


Link to post
Share on other sites

What about the regular expression way ?  :)

#Include <Array.au3>

$n = "0017-0008"

; get the line to a string
; assuming that in the file, it's the last line containing "0017-0008"
$txt = FileRead("gaplst.txt")
$res1 = StringRegExpReplace($txt, '(?s).*(' & $n & '\N+).*', "$1")
Msgbox(0,"", $res1)

; parse non whitespace sequences to an array
$res2 = StringRegExp($res1, '\S+', 3)
_ArrayDisplay($res2)

 

Share this post


Link to post
Share on other sites

@rkr,

Use it this way.

_StringSplit()

Func _StringSplit()
    Local $sString = StringSplit("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59", " ") ; Split the string using the delimiter " " and return the value.

    For $i = 1 To $sString[0]
        MsgBox(0, "", "String [" & $i & "] - " & $sString[$i])
    Next
EndFunc

All you need to do is replace the "$sString" with the line searched from my above posted second code.


Programming is "To make it so simple that there are obviously no deficiencies" or "To make it so complicated that there are no obvious deficiencies" by C.A.R. Hoare.

Share this post


Link to post
Share on other sites
18 hours ago, rkr said:

i was trying stringsplit to store each of them above as a vairable

$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , " ")

For $k = 1 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next


Func _StringSplitToVar($sStr , $delim)
    Local $aString = StringSplit($sStr , $delim)

    For $i = 1 To $aString[0]
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next

    return $aString[0]

EndFunc

 


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

Share this post


Link to post
Share on other sites
On 1/23/2018 at 7:38 AM, iamtheky said:
$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , " ")

For $k = 1 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next


Func _StringSplitToVar($sStr , $delim)
    Local $aString = StringSplit($sStr , $delim)

    For $i = 1 To $aString[0]
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next

    return $aString[0]

EndFunc

 

u nailed it....thanks.. but the spacing between the numbers are not same...and it varies

Edited by rkr
noticed that input is edited

Share this post


Link to post
Share on other sites
3 hours ago, rkr said:

the spacing between the numbers are not same...and it varies

So, the regex way... because it allows such a variation

$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , "\S+")

For $k = 0 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next

Func _StringSplitToVar($sStr , $what_to_get)
    Local $aString = StringRegExp($sStr , $what_to_get, 3)

    For $i = 0 To UBound($aString)-1
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next
    return UBound($aString)-1
EndFunc

 

Share this post


Link to post
Share on other sites
On ‎1‎/‎23‎/‎2018 at 7:38 AM, iamtheky said:
$NumberOfVars = _StringSplitToVar("0017-0008 0017 l2a 1 -18407.00 5110.90 0.00 0.03 -70735.59" , " ")

For $k = 1 to $NumberOfVars
    msgbox(0, '' , eval("StringToVar" & $k))
Next


Func _StringSplitToVar($sStr , $delim)
    Local $aString = StringSplit($sStr , $delim)

    For $i = 1 To $aString[0]
        assign("StringToVar" & $i , $aString[$i] , 2)
    Next

    return $aString[0]

EndFunc

 

thanks buddy, this helped me

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
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Colduction
      Hi guys!, i have a problem to convert Python code to AutoIt code, in fact i had not coded with Python yet!, this code is about permutation a string's case, i will be happy with your comments :)❤;

      Python code:
       
      # Python code to print all permutations # with respect to cases # Function to generate permutations def permute(inp): n = len(inp) # Number of permutations is 2^n mx = 1 << n # Converting string to lower case inp = inp.lower() # Using all subsequences and permuting them for i in range(mx): # If j-th bit is set, we convert it to upper case combination = [k for k in inp] for j in range(n): if (((i >> j) & 1) == 1): combination[j] = inp[j].upper() temp = "" # Printing current combination for i in combination: temp += i print(temp), # Driver code permute("Hello") # This code is contributed by Sachin Bisht
      My code in AutoIt:
      ; https://www.geeksforgeeks.org/permute-string-changing-case/ _PermuteCase("ABC") Func _PermuteCase($sText) If StringRegExp($sText, "^[A-Za-z]{1,}$") Then Local $iLength = StringLen($sText) ; Get length of the text. Local $iMaxPerm = 2 ^ $iLength ; Number of permutations is 2^n Local $sLow_Text = StringLower($sText) ; Converting string to lower case Local $asChrs = StringToASCIIArray($sLow_Text) ; Split the text into array of chars. For $i = 1 To $iMaxPerm Step 1 For $j = 0 To $asChrs[0] ;................................................... Next Next Else Return SetError(-1, 0, "Error: Input is incorrect!") EndIf EndFunc ;==>_PermuteCase  
       
       
       
       
       
      ====================== SOLUTION by @TheXman ======================
       
    • By careca
      This is another take on string triggers, triggers on specific strings.
      Able to simple text pasting,
      opening links (as long as there's a www. http:\\ or https:\\ at the beggining)
      and is able to open applications, if there is a parameter in the parameter field, it uses it.
      Shows your external, lan, and gateway ip's.
      Able to change system volume by a set percentage, reading from the inputbox the number the user sets, if 0 or empty uses system default.
      The 4 longer input fields at the bottom, represent the process scaning, the 2 to the left continuously scan for the process name,
      and the 2 to the right are executed when the process in the left is found.
      process 1 for app 1, example, look for notepad.exe and start paint.exe if notepad is found.
      I made this because the existing string trigger applications didn't do it for me.
      I did this for me, but if someone finds it useful all the better.
    • By jmp
      i am trying to get number from string using this code :
      #include <IE.au3> $oIE = _IEAttach ("Edu.corner") Local $aName = "Student name & Code:", $iaName = "0" Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.InnerText = $aName Then $iaName = $oTd.NextElementSibling.InnerText $iGet = StringRegExpReplace($iaName, "\D", "") EndIf Next MsgBox(0, "", $iGet) it was get number like 52503058
      But, I want to get only student code 5250. (Different student have different code, sometime its 3 digits, Sometime 4)

       
    • By Inpho
      Hi All,
      I intend on keeping custom functions/UDFs (works in progress) here; if anyone wants to use any code, feel free.
      String functions:
      #AutoIt3Wrapper_AU3Check_Parameters=-d -w- 1 -w 2 -w 3 -w 4 -w 5 -w 6 #include-once ; #FUNCTION# ==================================================================================================================== ; Name ..........: _DateTimeGet ; Description ...: Returns the date and time formatted for use in sortable filenames, logs, listviews, etc. ; Syntax ........: _DateTimeGet(iType = 1[, $bHumanFormat = False]) ; Parameters ....: $iType - [optional] an integer value. Default is 1. ; 1 - Date and time in file-friendly format; 20190115_113756 ; 2 - Date in file-friendly format; 20190115 ; 3 - Time in file friendly format; 113756 ; $bHumanFormat - [optional] a boolean value. Default is False. ; True - Includes slashes in the date and colons in the time with a space inbetween ; False - No slashes or colons included with an underscore inbetween ; Return values .: Success - String ; Failure - Sets @error to non-zero and returns an empty string ; Author ........: Sam Coates ; =============================================================================================================================== Func _DateTimeGet($iType = 1, $bHumanFormat = False) If $iType < 1 Or $iType > 3 Then Return (SetError(-1, 0, "")) ;; Param1: ;; 1 = Date and time in file friendly format: 20190115_113756 ;; 2 = Date in file friendly format: 20190115 ;; 3 = Time in file friendly format: 113756 ;; Param2: ;; True = Use human-readable format: 15/01/2019 11:37:56 Local $sTime = @HOUR & ":" & @MIN & ":" & @SEC Local $sDate = @MDAY & "/" & @MON & "/" & @YEAR If $iType = 1 Then If $bHumanFormat = False Then $sTime = StringReplace($sTime, ":", "") $sDate = StringReplace($sDate, "/", "") $sDate = StringTrimLeft($sDate, 4) & StringMid($sDate, 3, 2) & StringLeft($sDate, 2) Return ($sDate & "_" & $sTime) Else Return ($sDate & " " & $sTime) EndIf ElseIf $iType = 2 Then If $bHumanFormat = False Then $sDate = StringReplace($sDate, "/", "") $sDate = StringTrimLeft($sDate, 4) & StringMid($sDate, 3, 2) & StringLeft($sDate, 2) EndIf Return ($sDate) ElseIf $iType = 3 Then If $bHumanFormat = False Then $sTime = StringReplace($sTime, "/", "") EndIf Return ($sTime) EndIf EndFunc ;==>_DateTimeGet ; #FUNCTION# ==================================================================================================================== ; Name ..........: _FileToFileExtension ; Description ...: Returns a file extension from a filename/FQPN (Fully Qualified Path Name) ; Syntax ........: _FileToFileExtension($sPath) ; Parameters ....: $sPath - a string value. ; Return values .: Success - String ; Failure - Empty string as returned from StringTrimLeft() ; Author ........: Sam Coates ; =============================================================================================================================== Func _FileToFileExtension($sPath) Return (StringTrimLeft($sPath, StringInStr($sPath, ".", 0, -1))) EndFunc ;==>_FileToFileExtension ; #FUNCTION# ==================================================================================================================== ; Name ..........: _FileToFileName ; Description ...: Returns a filename from a FQPN (Fully Qualified Path Name) ; Syntax ........: _FileToFileName($sPath[, $bIncludeExtension = True]) ; Parameters ....: $sPath - a string value. ; $bIncludeExtension - [optional] a boolean value. Default is True. ; Return values .: Success - String ; Failure - Empty string as returned from StringLeft() ; Author ........: Sam Coates ; =============================================================================================================================== Func _FileToFileName($sPath, $bIncludeExtension = True) Local $sReturn = StringTrimLeft($sPath, StringInStr($sPath, "\", 0, -1)) If $bIncludeExtension = False Then $sReturn = StringLeft($sReturn, StringInStr($sReturn, ".", 0, -1) - 1) Return ($sReturn) EndFunc ;==>_FileToFileName ; #FUNCTION# ==================================================================================================================== ; Name ..........: _FileToFilePath ; Description ...: Returns a folder path from a FQPN (Fully Qualified Path Name) ; Syntax ........: _FileToFilePath($sPath) ; Parameters ....: $sPath - a string value. ; Return values .: Success - String ; Failure - Empty string as returned from StringLeft() ; Author ........: Sam Coates ; =============================================================================================================================== Func _FileToFilePath($sPath) Return (StringLeft($sPath, StringInStr($sPath, "\", 0, -1) - 1)) EndFunc ;==>_FileToFilePath ; #FUNCTION# ==================================================================================================================== ; Name ..........: _StringLeft ; Description ...: Searches for a string inside a string, then removes everything on the right of that string ; Syntax ........: _StringLeft($sString, $sRemove[, $iCaseSense = 0, $iOccurrence = 1]) ; Parameters ....: $sString - a string value. The string to search inside. ; $sRemove - a string value. The string to search for. ; $iCaseSense - an integer value. Flag to indicate if the operations should be case sensitive. ; $iOccurrence - an integer value. Which occurrence of the substring to find in the string. Use a ; negative occurrence to search from the right side. ; Return values .: Success - String ; Failure - Empty string as returned from StringLeft() ; Author ........: Sam Coates ; =============================================================================================================================== Func _StringLeft($sString, $sRemove, $iCaseSense = 0, $iOccurrence = 1) Return (StringLeft($sString, StringInStr($sString, $sRemove, $iCaseSense, $iOccurrence) - 1)) EndFunc ;==>_StringLeft ; #FUNCTION# ==================================================================================================================== ; Name ..........: _StringRandom ; Description ...: Returns a string of random characters ; Syntax ........: _StringRandom($iAmount[, $iType = 1]) ; Parameters ....: $iAmount - an integer value. Length of returned string ; $iType - [optional] an integer value. Default is 1. ; 1 - Return digits (0-9) ; 2 - Return hexadecimal (0-9, A - F) ; 3 - Return Alphanumeric upper (0-9, A - Z) ; 4 - Return Alphanumeric (0-9, A - Z, a - z) ; 5 - Return Alpha upper (A - Z) ; 6 - Return Alpha (A - Z, a - z) ; Return values .: Success - String ; Failure - Empty string and @error flag as follows: ; @error : 1 - $iAmount is not a positive integer ; 2 - $iType is out of bounds ; Author ........: Sam Coates ; =============================================================================================================================== Func _StringRandom($iAmount, $iType = 1) If $iAmount < 1 Or IsInt($iAmount) = 0 Then Return (SetError(-1, 0, "")) Local $sString = "" Local $iRandomLow = 1, $iRandomHigh = 62 #Tidy_Off Local Static $aCharId[63] = [0, Chr(48), Chr(49), Chr(50), Chr(51), Chr(52), Chr(53), Chr(54), Chr(55), Chr(56), Chr(57), Chr(65), Chr(66), Chr(67), _ Chr(68), Chr(69), Chr(70), Chr(71), Chr(72), Chr(73), Chr(74), Chr(75), Chr(76), Chr(77), Chr(78), Chr(79), Chr(80), _ Chr(81), Chr(82), Chr(83), Chr(84), Chr(85), Chr(86), Chr(87), Chr(88), Chr(89), Chr(90), Chr(97), Chr(98), Chr(99), _ Chr(100), Chr(101), Chr(102), Chr(103), Chr(104), Chr(105), Chr(106), Chr(107), Chr(108), Chr(109), Chr(110), Chr(111), _ Chr(112), Chr(113), Chr(114), Chr(115), Chr(116), Chr(117), Chr(118), Chr(119), Chr(120), Chr(121), Chr(122)] #Tidy_On If $iType = 1 Then ;; digits: 1 - 10 $iRandomHigh = 10 ElseIf $iType = 2 Then ;; hexadecimal: 1 - 16 $iRandomHigh = 16 ElseIf $iType = 3 Then ;; alnumupper: 1 - 36 $iRandomHigh = 36 ElseIf $iType = 4 Then ;; alnum: 1 - 62 $iRandomHigh = 62 ElseIf $iType = 5 Then ;; alphaupper: 11 - 36 $iRandomLow = 11 $iRandomHigh = 36 ElseIf $iType = 6 Then ;; alpha: 11 = 62 $iRandomLow = 11 $iRandomHigh = 62 Else Return (SetError(-2, 0, "")) EndIf For $i = 1 To $iAmount $sString &= $aCharId[Random($iRandomLow, $iRandomHigh, 1)] ;; append string with corresponding random character from ascii array Next Return ($sString) EndFunc ;==>_StringRandom ; #FUNCTION# ==================================================================================================================== ; Name ..........: _StringTrimLeft ; Description ...: Searches for a string inside a string, then removes everything on the left of that string ; Syntax ........: _StringTrimLeft($sString, $sRemove[, $iCaseSense = 0, $iOccurrence = 1]) ; Parameters ....: $sString - a string value. The string to search inside. ; $sRemove - a string value. The string to search for. ; $iCaseSense - an integer value. Flag to indicate if the operations should be case sensitive. ; $iOccurrence - an integer value. Which occurrence of the substring to find in the string. Use a ; negative occurrence to search from the right side. ; Return values .: Success - String ; Failure - Empty string as returned from StringTrimLeft() ; Author ........: Sam Coates ; =============================================================================================================================== Func _StringTrimLeft($sString, $sRemove, $iCaseSense = 0, $iOccurrence = 1) Return (StringTrimLeft($sString, StringInStr($sString, $sRemove, $iCaseSense, $iOccurrence) + StringLen($sRemove) - 1)) EndFunc ;==>_StringTrimLeft Examples:
      ConsoleWrite(_StringRandom(100, 6) & @CRLF) ConsoleWrite(_StringTrimLeft("C:\Windows\System32\cmd.exe", "C:\Windows\System32\") & @CRLF) ConsoleWrite(_StringLeft("C:\Windows\System32\cmd.exe", "cmd.exe") & @CRLF) ConsoleWrite(_FileToFileName("C:\Windows\System32\cmd.exe") & @CRLF) ConsoleWrite(_FileToFilePath("C:\Windows\System32\cmd.exe") & @CRLF) ConsoleWrite(_FileToFileExtension("C:\Windows\System32\cmd.exe") & @CRLF) ConsoleWrite(_StringRandom(6, 4) & "-" & _StringRandom(4, 4) & "-" & _StringRandom(4, 4) & "-" & _StringRandom(4, 4) & "-" & _StringRandom(6, 4)& @CRLF)  
    • By nacerbaaziz
      good morning sirs.
      please i have a request from you.
      i have an variable to Read a data from a file
      this data is Encrypted
      and when i read it i Decrypte it.
      for that i need a function to Write a ini data to string.
      ;#Function# ===================================================================================================================== ; Name............: _IniReadFromString ; Description.....: Returns the value of a key in a specific section of an ini-formatted string ; Syntax..........: _IniReadFromString($szInput, $szSection, $szKey, $Default) ; Parameters......: ;   $szInput - The string that contains data in ini format ;   $szSection   - The sectionname (just as in IniRead) ;   $szKey   - The keyname (just as in IniRead) ;   $Default - The default value if the key does not exist or reading failed (just as in IniRead) ; Return values ..: ;   Success  - Returns the read value ;   Failure  - Returns $Default ; Author .........: FichteFoll ; Remarks ........: Works for Unicode as well as for ANSI ; Related ........: IniRead, _IniReadSectionFromString ; Link ...........; See on top ; Example ........; $var = _IniReadFromString(StringFormat("[Sect]\r\nMyKey1=value1\r\nMyKey2=value2"), "Sect", "MyKey2", "no_value") ; =============================================================================================================================== Func _IniReadFromString($szInput, $szSection, $szKey, $Default) $szInput = StringStripCR($szInput) ;~  Local $aRegMl = StringRegExp($szInput, "\[" & __StringEscapeRegExp($szSection) & "\]\n+(?:[^\[].*?=.*\n)*" & __StringEscapeRegExp($szKey) & "=(.*)\n?(",3) Local $aRegMl = StringRegExp($szInput, "\[" & __StringEscapeRegExp($szSection) & "\]\n+(?:[^\[].*?=.*\n)*" & __StringEscapeRegExp($szKey) & "=(.*)\n?", 3) If @error Then Return SetError(1, 0, $Default) ; key not found    Return $aRegMl[0] EndFunc;==>_IniReadFromString ; ############################################################################################################################### ; =============================================== ; = Internal Use Only ; =============================================== Func __StringEscapeRegExp($szExp) Return StringRegExpReplace($szExp, "([\(\)\[\]\{\}\\\/\?\.\\|\+])", "\\$1") ; ()[]{}\/?.|+ EndFunc;==>__StringEscapeRegExp like this  function Read the ini from string.
       
       
      please ihelp me
      thanks in advance
×
×
  • Create New...