Jump to content

Stringregexpreplace A Specifc Iinstance In A String?


smashly
 Share

Recommended Posts

Hi,

Thank You for taking the time to read my post.

Could someone please post a brief example of using StringRegExpReplace() to replace a word at a specific count.

For example I'm trying to replace only the 2nd instance of the word "Dog" with "Turtle" in the string below.

$sStr = "CatDogMouseBirdHorseDogBirdHorseMouseBirdDogAnt"
Edited by smashly
Link to comment
Share on other sites

$sStr = "CatDogMouseBirdHorseDogBirdHorseMouseBirdDogAnt"

MsgBox(0,0,StringRegExpReplace($sstr, '(?s)(?U)' & _ ;(?s)will make . to match anything; (?U) makes repeating character Lazy[ie Now * is *?]
'(Dog)' & _ ; [First Group] The FirstMatch of the SearchString
'(.*)(\1)' & _ ; [Second Group] Match the least number of characters after which [Third Group] the first back-reference(i.e "Dog") is found
,'\1\2Turtle') & _ ; Replace the Third Group with Turtle
)

Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Link to comment
Share on other sites

  • Moderators

PhoenixXL,

Always a good idea to explain what is going on in the SRE - would you mind? ;)

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

M23,

I'll keep it in mind next time

I have added comments in the Code

BTW thanks for the advice :)

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Link to comment
Share on other sites

  • Moderators

PhoenixXL,

Thanks - I learnt a lot from that. :thumbsup:

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

In a more rudimentar way...

$sStr = "CatDogMouseBirdHorseDogBirdHorseMouseBirdDogAnt"
$sStrSplt = StringSplit($sStr, 'Dog', 1)
;MsgBox(64, '', ' 0 '&$sStrSplt[0]&' | 1 '&$sStrSplt[1]&' | 2 '&$sStrSplt[2]&' | 3 '&$sStrSplt[3]&' | 4 '&$sStrSplt[4])
MsgBox(64, '', $sStrSplt[1]&'Dog'&$sStrSplt[2]&'Turtle'&$sStrSplt[3]&$sStrSplt[4])
Spoiler

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Link to comment
Share on other sites

Even though you wanted an example using SRER, I thought I would let you know that not everything has to be done with SRE if you don't feel like a guru. Here is an example using AutoIt native string functions.

Local Const $sFind = 'Dog', $iOccurrence = 2
Local $sText = 'CatDogMouseBirdHorseDogBirdHorseMouseBirdDogAnt'
Local $iPosition = StringInStr($sText, $sFind, 2, $iOccurrence) ; Case-insensitive, second occurance.

; Left side of Dog.
Local $sLeft = StringLeft($sText, $iPosition - 1)
ConsoleWrite('Left part: ' & $sLeft & @CRLF)

; Right side of Dog.
Local $sRight = StringMid($sText, $iPosition + StringLen($sFind), StringLen($sText) - $iPosition)
ConsoleWrite('Right part: ' & $sRight & @CRLF)

ConsoleWrite('Final: ' & $sLeft & 'Turtle' & $sRight & @CRLF)

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

For more examples of such Regular Expressions look

A Bit Extension of StringReplace with RegEx

#include <Array.au3>


;Replaces the 2nd Occurence with the ReplaceString [Case - Sensitive]
$sStr = RegEx_StringReplace ("CatDogMouseBirdHorseDogBirdHorseMouseBirdDogAnt", 'Dog', 'Turtle', 0, 2, False) ;True will cause 1st and 2nd Occurence to get replaced
MsgBox (0, @extended,  $sStr )



Func RegEx_StringReplace($sString, $sSearch, $sReplace, $iInSensitive = 1, $iOccurrence = 0, $iContinue = False, $iRegEx = False)
Local $iReverse = False
;Insensitiveness
If $iInSensitive Then
$iInSensitive = '(?i)'
Else
$iInSensitive = ''
EndIf
If $iOccurrence < 0 Then
;Check for Negative occurance
$iReverse = True
$iOccurrence *= -1
$sString = RegEx_StringReverse($sString)
EndIf
;Check for special characters
If Not $iRegEx Then
CheckPattern( $sSearch )
If ($iOccurrence - 1) And Not $iContinue Then
$sSearch = '(?s)' & $sSearch & '((.*?)(\1)){' & $iOccurrence - 1 & '}'
$sReplace = '\1\3' & $sReplace
EndIf
EndIf
;main function
Local $aRet = StringRegExpReplace($sString, $iInSensitive & $sSearch , $sReplace, $iOccurrence)
Local $iExt = @extended
If Not $iContinue Then $iExt = 1
If $iReverse Then $aRet = RegEx_StringReverse($sString)
Return SetExtended($iExt, $aRet)
EndFunc ;==>RegEx_StringReplace

Func RegEx_StringReverse($sString, $iStart = 0, $iEnd = 0)
Local $sStart = '', $sEnd = ''
;Get the Start which would not be reversed
If $iStart > 0 Then $sStart = RegEx_StringMid($sString, 0, $iStart)
;Get the Start which would not be reversed
If $iStart + $iEnd < RegEx_StringLen($sString) Then $sEnd = RegEx_StringMid($sString, RegEx_StringLen($sString) - ($iStart + $iEnd))
;The Original String which has to be reversed
$sString = RegEx_StringMid($sString, $iStart, $iEnd)
;main function
Local $aRet = StringRegExp($sString, '(?s)(.)', 3)
_ArrayReverse($aRet)
Return $sStart & _ArrayToString($aRet, '') & $sEnd
EndFunc ;==>RegEx_StringReverse

Func RegEx_StringLen($sString)
;Replace Each Character
StringRegExpReplace($sString, '(?s)(.)', '')
;Return the Number of replacements
Return @extended
EndFunc ;==>RegEx_StringLen

Func RegEx_StringMid($sString, $iStart = 0, $iEnd = 0) ;First Char = 0
;If Start and End are 0 then Return the whole string
If Not BitOR($iStart, $iEnd) Then Return $sString
;If Out of Bounds then Return
If $iStart + $iEnd > RegEx_StringLen($sString) Then Return SetError(1, 0, $sString)
If $iStart > RegEx_StringLen($sString) Then Return SetError(2, 0, $sString)
If $iEnd < 0 Then Return SetError(3, 0, $sString)
If $iStart < 0 Then Return SetError(4, 0, $sString)
;Carry Out the Main Function
If $iStart Then $sString = StringRegExpReplace($sString, '(?s)(.{' & $iStart & '})', '', 1)
If $iEnd Then $sString = StringRegExpReplace($sString, '(?s)(.{' & $iEnd & '})(.*)', '\1', 1)
Return $sString
EndFunc ;==>RegEx_StringMid

Func CheckPattern (ByRef $sString )
;enclose withing sets so that special character lose their meaning
$sString = '(' & StringRegExpReplace ( $sString, '(?s)(.)', '[\1]' ) & ')'
Return 1
EndFunc
Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

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...