Jump to content

Can $stringregexp return a character number?


 Share

Recommended Posts

Hi all. Is there any simple/quick method (function or otherwise) to search for a string for a substring using wildcards and such (like is done with the function stringregexp), and, when a match is found, have it return the character number in the string of the match? Edit: For example, searching the string "I am 5 years old" for anything matching d* would return 6 (i.e. the first string of numbers occurs at the 6th character in the string).

I'm quite sure stringregexp can only return True or False, and functions like StringinString seem to require an exact string to look for. I've searched the forums and web, but haven't found anything so I thought I'd ask. Such a search may provide a large amount of hits, and may possibly get a little ambiguous or infinite-y. For example, searching the string "123" for anything matching d* could conceivably return 6 hits, right? Three hits would be at position 1, two hits at position 2, and one hit at position 3. Or I maybe I'm misunderstanding the search protocols.

Edited by cag8f
Link to comment
Share on other sites

This may need adjustment, depending on your exact use case:

Local $s = "I am more than 5 years old"

Local $iPos = StringLen(StringRegExpReplace($s, "(.*?)\d.*", "$1")) + 1
ConsoleWrite("Pattern found at position " & $iPos & @LF)

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)

Link to comment
Share on other sites

  • Moderators

cag8f,

You can do what you want very easily like this: ;)

$sString = "I am 5 years old"

StringRegExp($sString, "\d", 1) ; Use flag = 1 to get offset into @extended

; Note the offset is to the beginnning of the next character AFTER the found group
MsgBox(0, "Digit Location", "Digits begin at character " & (@extended - 1))

All clear? :)

M23

Edit: Bonjour jchd! :D

Edited by Melba23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Salut Melba23

In the general case you need to subtract the length of the matched substring, not 1. -1 is only valid iff the pattern matches exactly 1 character.

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)

Link to comment
Share on other sites

  • Moderators

jchd,

Quite right as usual when it comes to RegExes. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

$sText = 'only 7609   word text'

$aSection = StringRegExp($sText, '(?s)(\d+)(\h+)([A-Za-z]+)', 2)
If Not @error Then
    $iEndPattern = @extended
    $iStartPattern = $iEndPattern - StringLen($aSection[0])
    $iEndSection3 = $iEndPattern - StringLen($aSection[3])
    $iEndSection2 = $iEndSection3 - StringLen($aSection[2])
    $iEndSection1 = $iEndSection2 - StringLen($aSection[1])
    MsgBox(0, 'info', _
            'String = |' & $sText & '|' & @LF & _
            '[0]=(' & $aSection[0] & ')' & @LF & _
            '[1]=(' & $aSection[1] & ')' & @LF & _
            '[2]=(' & $aSection[2] & ')' & @LF & _
            '[3]=(' & $aSection[3] & ')' & @LF & @LF & _
            'Start' & @TAB & 'ch=' & $iStartPattern & @TAB & ' ->|' & StringTrimLeft($sText, $iStartPattern - 1) & @LF & _
            'End' & @TAB & 'ch=' & $iEndPattern & @TAB & ' ->|' & StringTrimLeft($sText, $iEndPattern - 1) & @LF & _
            'Sec3' & @TAB & 'ch=' & $iEndSection3 & @TAB & ' ->|' & StringTrimLeft($sText, $iEndSection3 - 1) & @LF & _
            'Sec2' & @TAB & 'ch=' & $iEndSection2 & @TAB & ' ->|' & StringTrimLeft($sText, $iEndSection2 - 1) & @LF & _
            'Sec1' & @TAB & 'ch=' & $iEndSection1 & @TAB & ' ->|' & StringTrimLeft($sText, $iEndSection1 - 1))
EndIf

Link to comment
Share on other sites

Thanks all! Sorry for the late reply--I was expecting to receive email updates when replies were posted. I'll check my settings on that. Otherwise, there look to be some very helpful advice here.

Link to comment
Share on other sites

Ha! I think I got one of these Klingon (SRE) things right...

Gui version

#include <WindowsConstants.au3>
#include <EditConstants.au3>
#include <StaticConstants.au3>
#include <GUIConstantsEx.au3>
#include <array.au3>

#AutoIt3Wrapper_Add_Constants=n

local $gui010    =    guicreate('String Finder',600,700)
local $aSize    =    wingetclientsize($gui010)
                    guictrlcreatelabel('Hit <ENTER> to search!',20,20,500,40)
                    guictrlsetfont(-1,24,800)
                    guictrlcreatelabel('Search....',20,100,300,20)
                    guictrlsetfont(-1,12,800)
local $inp010    =    guictrlcreateinput('',20,120,$aSize[0]-40,20)
                    guictrlsetfont(-1,9,600,-1,'Courier New')
                    guictrlcreatelabel('For...',20,160,100,20)
                    guictrlsetfont(-1,12,800)
local $inp020    =    guictrlcreateinput('',20,180,$aSize[0]-40,20)
local $edt010    =    guictrlcreateedit('',20,220,$aSize[0]-40,350,bitor($WS_VSCROLL,$es_readonly))
                    guictrlsetfont(-1,8.5,600,-1,'Courier New')
                    guictrlcreatelabel('Result',20,$aSize[1]-100,$aSize[0]-40,20)
local $result    =    guictrlcreatelabel('',20,$aSize[1]-80,$aSize[0]-40,25, $ss_sunken)
                    guictrlsetfont(-1,10,800,-1,'Lucinda Console')
                    guictrlcreatelabel('SRE (just for debugging)',20,$aSize[1]-50,$aSize[0]-40,20)
local $sre        =    guictrlcreatelabel('',20,$aSize[1]-30,$aSize[0]-40,25, $ss_sunken)
                    guictrlsetfont(-1,10,800,-1,'Lucinda Console')
                    guisetstate()
local $enter    =    guictrlcreatedummy()
                    guictrlsetdata($inp010,'Where is the 5 "#$%^@''{[(". year *old* scotch?')                      ; <-----   test string
                    guictrlsetstate($inp020,$gui_focus)

Dim $aAccelerators[1][2] = [["{ENTER}", $Enter]]
GUISetAccelerators($aAccelerators)

while 1
    switch guigetmsg()
        case $gui_event_close
            Exit
        case $enter
            guictrlsetdata($edt010,'         12345678901234567890123456789012345678901234567890' & @crlf,1)      ; <-----   ruler
            guictrlsetdata($result,(_FindString(guictrlread($inp010),guictrlread($inp020))))
            guictrlsetstate($inp020,$gui_focus)
    EndSwitch
WEnd

func _FindString($str, $srchstr)

    guictrlsetdata($edt010,'String = ' & $str & @crlf & 'Search = ' & $srchstr & @crlf,1)

    $srchstr = stringregexpreplace($srchstr,'[\^\.\*\?\$\[\]\(\)]','\\$0')    ; precede reserved chars with a '\'

    local $pattern = '(?si)' & $srchstr

    guictrlsetdata($sre,'Pattern = ' & $pattern)

    local $aSrch = StringRegExp($str, $pattern, 1)

    switch @error
        case 0
            return 'Pattern found at ' & @extended - stringlen($aSrch[0])
        case 1
            return 'Not Found'
        case 2
            return 'Bad pattern, array is invalid. Pattern error at offset ' &  @extended
    endswitch

endfunc

and a function version (without all the gui shit)

local $source_string = 'Happy Easter!  Try not to "#$%@^&?" kill someone today.'
ConsoleWrite(_find_position($Source_string,'!') & @LF)
ConsoleWrite(_find_position($Source_string,'today') & @LF)
ConsoleWrite(_find_position($Source_string,'^') & @LF)
ConsoleWrite(_find_position($Source_string,'.') & @LF)
ConsoleWrite(_find_position($Source_string,'"') & @LF)

func _find_position($source_string,$srch_string)

    $srch_string = stringregexpreplace($srch_string,'[\^\.\*\?\$\[\]\(\)]','\\$0')
    local $pattern = '(?si)' & $srch_string
    local $aSrch = StringRegExp($source_string, $pattern, 1)

    switch @error
        case 0
            return 'Pattern found at ' & @extended - stringlen($aSrch[0])
        case 1
            return 'Not Found'
        case 2
            return 'Bad pattern, array is invalid. Pattern error at offset ' &  @extended
    endswitch

endfunc
Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...