Jump to content

Validating URL using RegExp


Recommended Posts

Greetings,

I'm trying to validate a URL entry using RegExp. I've been using the pattern "\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]" successfully in other languages but it seems to not work in AutoIt3. This pattern is meant to match any valid URL, but in my particular case I only need to check for http/https. Below is a snippet I'm using:

If Not StringRegExp(GUICtrlRead($inp_Url), "https?://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]") Or GUICtrlRead($inp_Url) = "" Then
    MsgBox(16, "Invalid URL error", "URL " & GUICtrlRead($inp_Url) & @LF & "either blank or invalid." & @LF & @LF & "Error: " & @error, 10)
Then

No matter what I inform, StringRegExp() always returns 0 (zero). What am I missing? TIA.

Best,
Euler

Link to comment
Share on other sites

I don't think you want that to be case-sensitive so put (?i) at the beginning of the expression.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

There is another way to check an URL :)

Func _IsValidURL($sURL)
    ; ProgAndy
    Local $aRes = DllCall("urlmon.dll", "long", "IsValidURL", "ptr", 0, "wstr", $sURL, "dword", 0)
    If @error Then Return SetError(1,0,False)
    Return $aRes[0]=0
EndFunc

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Link to comment
Share on other sites

I don't think you want that to be case-sensitive so put (?i) at the beginning of the expression.

Thanks for answering, George.

Yeah, you're right! I always forget that in PCRE. While regexes are mostly case-insensitive, this doesn't stands for PCRE. Thanks for the heads-up. BTW, the pattern works now and a bit better after including "^" and a "$" at the beginning and at the end of the pattern, as I don't need multiline matching.

Testing my pattern with StringRegExpGUI.au3 did also help a lot. :)

Thanks again. :)

Best,
Euler

Link to comment
Share on other sites

There is another way to check an URL :P

Func _IsValidURL($sURL)
    ; ProgAndy
    Local $aRes = DllCall("urlmon.dll", "long", "IsValidURL", "ptr", 0, "wstr", $sURL, "dword", 0)
    If @error Then Return SetError(1,0,False)
    Return $aRes[0]=0
EndFunc

Thanks for replying, ProgAndy. :)

Unfortunately, your code above always returns False no matter what URL I provide. I have urlmon.dll's directory on %PATH%. I'll fiddle with it later on.

Thanks much. :)

Best,
Euler

Link to comment
Share on other sites

I didn't get a problem with the Function provided by ProgAndy.

Edited by guinness

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

Thanks for answering, George.

Yeah, you're right! I always forget that in PCRE. While regexes are mostly case-insensitive, this doesn't stands for PCRE. Thanks for the heads-up. BTW, the pattern works now and a bit better after including "^" and a "$" at the beginning and at the end of the pattern, as I don't need multiline matching.

Testing my pattern with StringRegExpGUI.au3 did also help a lot. :)

Thanks again. :)

I think you might also have been able to use \w to replace the A-Z0-9.

For testing take a look at the PCRE Toolkit in my signature.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

I didn't get a problem with the Function provided by ProgAndy.

Hi guiness,

I don't know why it didn't deliver here. I looked into DllCall and urlmon.dll syntax and all seems fine. Must take a rest before hacking it again. Anyway, I just used copy and paste. :)

Best,
Euler

Link to comment
Share on other sites

  • Moderators

Running on x64 OS?

Try this and tell me if it works now:

#include <WinAPI.au3>

If Not __FileExists("urlmon.dll") Then
    MsgBox(16 + 262144, "Error", "urlmon.dll doesn't exist!")
    Exit 1
EndIf

Global $gf_IsURL = _IsValidURL("http://www.autoitscript.com/forum/topic/126420-validating-url-using-regexp/")
If @error Then
    MsgBox(16 + 262144, "Error", _WinAPI_GetLastErrorMessage())
    Exit 2
EndIf

If Not $gf_IsURL Then
    MsgBox(16 + 262144, "Error", "Invalid URL")
    Exit 3
EndIf

MsgBox(64, "Info", "URL is Valid")
Exit 0

Func _IsValidURL($sURL)
    ; ProgAndy
    Local $aRes = DllCall("urlmon.dll", "long", "IsValidURL", "ptr", 0, "wstr", $sURL, "dword", 0)
    If @error Then Return SetError(1,0,False)
    Return $aRes[0]=0
EndFunc

; for x64 and x86
Func __FileExists($s_file)

    If @OSArch = "X86" Then Return FileExists($s_file)

    ; if we're not dealing with system dir, try to do normal
    If StringLeft($s_file, StringLen(@SystemDir)) <> @SystemDir Then
        ; if we fail try disabling redirection
        If FileExists($s_file) Then Return 1
    EndIf

    ; we already checked local file, now check system dir
    If Not StringRegExp($s_file, "[:\\/]") Then
        $s_file = @SystemDir & "\" & $s_file
    EndIf

    Local $t_int = DllStructCreate("int")
    Local $p_int = DllStructGetPtr($t_int)

    ; disable redirection
    DllCall("kernel32.dll", "int", "Wow64DisableWow64FsRedirection", "ptr", $p_int)
    Local $i_ret = FileExists($s_file)
    DllCall("kernel32.dll", "int", "Wow64RevertWow64FsRedirection", "ptr", $p_int)

    Return $i_ret
EndFunc

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

It works on x64, but so did the other Function! :)

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

  • Moderators

It works on x64, but so did the other Function! :)

You probably disabled redirection already, I have to programmatically do it. Win7 x64, it failed until I did the above for me.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

  • 2 weeks later...

Running on x64 OS?

No, WinXP-32 Pro. Anyway, I found why it failed: urlmon.dll wasn't loaded (though available from %PATH% at C:\Windows\System32). Either copying urlmon.dll to working dir, or addressing it by a absolute path did work ok as it did after loading DLL with DllOpen.

Both methods are working now. Thanks to all who help. :)

Best,
Euler

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