Sign in to follow this  
Followers 0
AutoBert

extending a RegEx Pattern

7 posts in this topic

#1 ·  Posted (edited)

The idea to use translation api:

i used the script from @mikell to build this func:

Func _Translate($sFrom, $from, $to)
    ;thanks to mikell (autoitscript.com)
    ;https://www.autoitscript.com/forum/topic/182893-prompt-me-how-to-see-the-text-in-the-translation-boxhttpstranslategooglecom/?do=findComment&comment=1313423
    Local $url = "https://translate.googleapis.com/translate_a/single?client=gtx"
    $url &= "&sl=" & $from & "&tl=" & $to & "&dt=t&q=" & $sFrom

    Local $oHTTP = ObjCreate("Microsoft.XMLHTTP")
    $oHTTP.Open("POST", $url, False)
    $oHTTP.Send()
    Local $sData = $oHTTP.ResponseText
    $sData = StringRegExpReplace($sData, '.*?\["(.*?)"[^\[]*', "$1" & @CRLF)
    Return $sData
EndFunc   ;==>_Translate

when i call this func with:

$sText='AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required!'
MsgBox(64,'',_Translate($sText,'en','de'))

nearly all is :thumbsup: seeing here:

79_Done.jpg

only the "!" is wrong "\" but when using 'auto' instead of 'en' the result is:

80_Done.jpg

2 lines are appended. So my question is, is it possible to extend the pattern (i never worked with regex) and in best case setting @extended with the detected language?

@Trong: as you can see yet i am returning translated text and don't use GuiCtrlSetData to assign it to a EditBox.

Edited by AutoBert

Share this post


Link to post
Share on other sites

This is tricky, using one expression only there is a risk of 'catastrophic backtracking'
Personally I'd prefer to do it in 2 steps and get a resulting array (a bit longer but reliable)

Func _Trad($mytext, $from, $to)
   $url = "https://translate.googleapis.com/translate_a/single?client=gtx"
   $url &= "&sl=" & $from & "&tl=" & $to & "&dt=t&q=" & $mytext
   $oHTTP.Open("POST", $url, False)
   $oHTTP.Send()
   $sData = $oHTTP.ResponseText()
   Local $aData[2]  ; text & language
   $tmp = StringRegExpReplace($sData, '\[\[(.*?)\]\].*', "$1")
   $aData[0] = StringRegExpReplace($tmp, '.*?\["(.*?)(?<!\\)"[^\[]*', "$1" & @crlf)
   $tmp2 = StringReplace($sData, $tmp, "")
   $aData[1] = StringRegExpReplace($tmp2, '.*?"([^"]+).*', "$1")
   Return $aData
EndFunc

 

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Using this:

#include <Array.au3>

$sText='AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required!'
$sData=_Trad($sText,'auto','de')
Switch @extended
    case 1
        $sLang='en'
    case 2
        $sLang='de'
EndSwitch

MsgBox(64,'Done ('&$sLang&')',$sData)

Func _Trad($mytext, $from, $to)
   Local $url = "https://translate.googleapis.com/translate_a/single?client=gtx"
   $url &= "&sl=" & $from & "&tl=" & $to & "&dt=t&q=" & $mytext
    Local $oHTTP = ObjCreate("Microsoft.XMLHTTP")
   $oHTTP.Open("POST", $url, False)
   $oHTTP.Send()
   $sData = $oHTTP.ResponseText()
   ConsoleWrite('====================================================================='&@CRLF)
   ConsoleWrite($sData&@CRLF)
   ConsoleWrite('====================================================================='&@CRLF)
   Local $aData[2]  ; text & language
   $tmp = StringRegExpReplace($sData, '\[\[(.*?)\]\].*', "$1")
   $aData[0] = StringRegExpReplace($tmp, '.*?\["(.*?)(?<!\\)"[^\[]*', "$1" & @crlf)
   $tmp2 = StringReplace($sData, $tmp, "")
   $aData[1] = StringRegExpReplace($tmp2, '.*?"([^"]+).*', "$1")
   ;_ArrayDisplay($aData)
   if $aData[1] <> '' Then SetError(0, 1); set later the Index getting from Array of supported languages.
   Return $aData[0]
EndFunc

the problem with the 2 appended lines (detected language) is solved, but in the "De-ESCaping" of the text the problem is a little bit better. In the nicght i don't saw that instead of expected :

Quote

ohne störendes "Runtimes" erforderlich!

result was:

Quote

ohne störendes \

now it's:

Quote

ohne störendes \"Runtimes\" erforderlich!

81_Done (en).jpg

seems \"  ==> " is the only problem left. But i can do this with StringReplace. The greates problem isn't clientside, so the user have to modify the result bevor using with C&P.

Edited by AutoBert

Share this post


Link to post
Share on other sites

Yes the quotes included in the text are escaped reason why I used  "(.*?)(?<!\\)" 
A StringReplace on the final text is the solution indeed
 

Share this post


Link to post
Share on other sites

Without your help i had to wrote whole translate func with String*-funcs and _StringBetween, so >95% work is done by you :thumbsup:  and the one needed StringReplace is already added:

Func _TranslateEX($mytext, $from, $to)
    ;thanks to mikell (autoitscript.com)
    ;idea https://www.autoitscript.com/forum/topic/182893-prompt-me-how-to-see-the-text-in-the-translation-boxhttpstranslategooglecom/?do=findComment&comment=1313423
    ;and https://www.autoitscript.com/forum/topic/183054-extending-a-regex-pattern/?do=findComment&comment=1314560
    Local $url = "https://translate.googleapis.com/translate_a/single?client=gtx"
    $url &= "&sl=" & $from & "&tl=" & $to & "&dt=t&q=" & $mytext
    Local $oHTTP = ObjCreate("Microsoft.XMLHTTP")
    $oHTTP.Open("POST", $url, False)
    $oHTTP.Send()
    $sData = $oHTTP.ResponseText()
    Local $aData[2] ; text & language
    $tmp = StringRegExpReplace($sData, '\[\[(.*?)\]\].*', "$1")
    $aData[0] = StringRegExpReplace($tmp, '.*?\["(.*?)(?<!\\)"[^\[]*', "$1" & @CRLF)
    $aData[0] = StringReplace($aData[0], '\"', '"')
    ;ConsoleWrite('====================================================================='&@CRLF)
    ;ConsoleWrite($aData[0]&@CRLF)
    ;ConsoleWrite('====================================================================='&@CRLF)
    $tmp2 = StringReplace($sData, $tmp, "")
    $aData[1] = StringRegExpReplace($tmp2, '.*?"([^"]+).*', "$1")
    ;_ArrayDisplay($aData)
    #cs
    If $aData[1] <> '' Then
        _GetLangIndex($aData[1])
        SetError(0, @extended); set later Index in Array of supported languages.
    EndIf
    #ce
    Return $aData[0]
EndFunc   ;==>_TranslateEX

Thank's a lot.

Share this post


Link to post
Share on other sites

Using GuiRegisterMsg  you can even do simultaneous translation, which works (I tried it) super nice - until google fires a captcha because of unusual excessive traffic for your IP  :D

Share this post


Link to post
Share on other sites
2 hours ago, mikell said:

Using GuiRegisterMsg  you can even do simultaneous translation,

I have 2 Editcontrols one with the text to be translated, the other with the translated responcetext. So there is no need to translate simulataneous. The whole script is thougt as a example, showing how to build a script, changing tooltips in depency of the choosen language.

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  
Followers 0

  • Similar Content

    • ViciousXUSMC
      By ViciousXUSMC
      So I ran into this crazy "program" that cant be uninstalled via WMI, MSIExec, etc.
      The only way to uninstall it was from Add/Remove programs manually... Or I found if you find it in the registry under HKCU and run the  uninstall string, it will also uninstall.
      However the string in the registry cant be run directly in a cmd window because of the format errors.
      It has spaces without quotations, it has invalid characters, etc, etc 
      I know things run different when executed in the registry, so maybe there is a way I can run the regsitry key just like how the system does?  If so chime in.
      Otherwise I did this a crude way using several stringregexpreplace() functions and have it working.
      The solution feels so barbaric and crude that I wanted to post it so some of you guys better than me can clean up the code, maybe offer alternative ways to do it, or reduce the number of times I process the string.
      Here is the string right out of the registry:
      c:\Program Files\Common Files\Microsoft Shared\VSTO\10.0\VSTOInstaller.exe /Uninstall file:///C:/Users/it022565/AppData/Local/Temp/OOBAXTOWordAddIn/ApplicationXtender.AXTO.Word.vsto Here is my cave man scripting to turn this into a run able string.
       
      Func _UninstallOld() For $i = 1 to 100 ;Enumerate Registry $sEnumBase = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" ;Look in HKCU for the uninstall string for the old version $sEnum = RegEnumKey($sEnumBase, $i) If @Error Then Return If $iDebug = 1 Then MsgBox(0, "", $sEnum) If StringInStr(RegRead($sEnumBase & $sEnum, "DisplayName"), "Word Addin") Then ExitLoop Next If $iDebug = 1 Then MsgBox(0, "", $sEnum) $sKey = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" & $sEnum $sKey2 = RegRead($sKey, "UninstallString") If $iDebug = 1 Then MsgBox(0, "Original Install Location", $sKey2) $sKey3 = StringRegExpReplace($sKey2, "(?i)(c:.*exe)", '"$1"') If $iDebug = 1 Then MsgBox(0, "", $sKey3) $sKey4 = StringRegExpReplace($sKey3, "(?i)file:///", "") If $iDebug = 1 Then MsgBox(0, "", $sKey4) $sKey5 = StringRegExpReplace($sKey4, "%20", " ") If $iDebug = 1 Then MsgBox(0, "", $sKey5) $sKey6 = StringRegExpReplace($sKey5, '(?i)((?<!")c:.*vsto)', '"$1"') If $iDebug = 1 Then MsgBox(0, "", $sKey6) RunWait(@ComSpec & ' /c ' & '"' & $sKey6 & ' /s"', "", @SW_HIDE) EndFunc Basically step by step I add quotations, strip bad characters, etc.  Kind of proud for using look behind for once
      Looking forward to what you guys come up with.
    • VIP
      By VIP
      Need help to make function better  with full infomation
      #include <Array.au3> #include <File.au3> _TEST(@ScriptFullPath) _TEST("A:") _TEST("A:\B.c") _TEST("D:\E\F\") _TEST("G:\H/../J.k/") _TEST("M:\N\k..J.k") _TEST("D:\E\F\..\G\G\I..J.K.M") Func _TEST($sFilePath) Local $sDrive = "", $sFullPathDir = "", $sDirPath = "", $sDirName = "", $sFileName = "", $sFileNameExt = "", $sExtension = "", $sExt = "" Local $aPathSplit = _PathSplitByRef($sFilePath, $sDrive, $sFullPathDir, $sDirPath, $sDirName, $sFileName, $sFileNameExt, $sExtension, $sExt) ConsoleWrite("!Path IN : " & $sFilePath & @CRLF) ; C:\Windows\System32\etc\hosts.exe ConsoleWrite("- Driver : " & $sDrive & @CRLF) ; C: ConsoleWrite("- DirPath : " & $sFullPathDir & @CRLF) ; C:\Windows\System32\etc\etc ConsoleWrite("- DirPath : " & $sDirPath & @CRLF) ; \Windows\System32\etc\ ConsoleWrite("- DirName : " & $sDirName & @CRLF) ; etc ConsoleWrite("- FileName : " & $sFileName & @CRLF) ; hosts ConsoleWrite("- FileNameExt: " & $sFileNameExt & @CRLF) ; hosts.exe ConsoleWrite("- Extension : " & $sExtension & @CRLF) ; .exe ConsoleWrite("- Ext : " & $sExt & @CRLF & @CRLF) ; exe ;~ ConsoleWrite("!Path IN : " & $aPathSplit[0] & @CRLF) ; C:\Windows\System32\etc\hosts.exe ;~ ConsoleWrite("- Driver : " & $aPathSplit[1] & @CRLF) ; C: ;~ ConsoleWrite("- DirPath : " & $aPathSplit[2] & @CRLF) ; C:\Windows\System32\etc\etc ;~ ConsoleWrite("- DirPath : " & $aPathSplit[3] & @CRLF) ; \Windows\System32\etc\ ;~ ConsoleWrite("- DirName : " & $aPathSplit[4] & @CRLF) ; etc ;~ ConsoleWrite("- FileName : " & $aPathSplit[5] & @CRLF) ; hosts ;~ ConsoleWrite("- FileNameExt: " & $aPathSplit[6] & @CRLF) ; hosts.exe ;~ ConsoleWrite("- Extension : " & $aPathSplit[7] & @CRLF) ; .exe ;~ ConsoleWrite("- Ext : " & $aPathSplit[8] & @CRLF) ; exe ;~ _ArrayDisplay($aPathSplit, "_PathSplit of " & $sFilePath) EndFunc ;==>_TEST Func _PathSplitByRef($sFilePath, ByRef $sDrive, ByRef $sFullPathDir, ByRef $sDirPath, ByRef $sDirName, ByRef $sFileName, ByRef $sFileNameExt, ByRef $sExtension, ByRef $sExt) If StringInStr($sFilePath,"..") Then $sFilePath=_PathFull($sFilePath) Local $aPartOfPath=StringRegExp($sFilePath, "^\h*((?:\\\\\?\\)*(\\\\[^\?\/\\]+|[A-Za-z]:)?(.*[\/\\]\h*)?((?:[^\.\/\\]|(?(?=\.[^\/\\]*\.)\.))*)?([^\/\\]*))$", $STR_REGEXPARRAYMATCH) ;~ If @error Then ReDim $aPartOfPath[9] ;~ $aPartOfPath[0] = $sFilePath ;~ EndIf $aPartOfPath[0] = $sFilePath ; C:\Windows\System32\etc\hosts.exe $sDrive = $aPartOfPath[1] ; C: $sFullPathDir = $aPartOfPath[1] & $aPartOfPath[2] ; C:\Windows\System32\etc If StringLeft($aPartOfPath[2], 1) == "/" Then $sDirPath = StringRegExpReplace($aPartOfPath[2], "\h*[\/\\]+\h*", "\/") Else $sDirPath = StringRegExpReplace($aPartOfPath[2], "\h*[\/\\]+\h*", "\\") EndIf $aPartOfPath[2] = $sFullPathDir ; C:\Windows\System32\etc $sDirName=StringReplace($sDirPath,"\","") $sDirName=StringReplace($sDirPath,"/","") $sFileName = $aPartOfPath[3] ; hosts $aPartOfPath[5] = $sFileName ; hosts $sExtension = $aPartOfPath[4] ; .exe $aPartOfPath[7] = $sExtension ; .exe $aPartOfPath[3] = $sDirPath ; \Windows\System32\etc\ $aPartOfPath[4] = $sDirName ; etc $aPartOfPath[6] = $sFileName & $sExtension ; hosts.exe $sFileNameExt = $aPartOfPath[6] ; hosts.exe $sExt = StringReplace($sExtension,".","") ; exe $aPartOfPath[8] = $sExt ; exe Return $aPartOfPath EndFunc ;==>_PathSplitByRef  
    • hawkair
      By hawkair
      Hi
      I am trying to insert line numbers in to a string
      with this script
      Func _MyInc () Static Local $i = 0 $i += 1 Return $i EndFunc Exit _InsertLines() Func _InsertLines()     $String = "A" & @CRLF & "B" & @CRLF & "C" & @CRLF & "D" $NewString =  Execute("'" & StringRegExpReplace($String,"[\r\n]*",  "' & _MyInc () & '\1" ) & "'") MsgBox (0, "", $NewString) EndFunc but I get this:
      1A23B45C67D8
      I never really could master how Execute works here and I always get some working example and make substitutions.
      But this is the closest i could get...
       
    • ViciousXUSMC
      By ViciousXUSMC
      I was working on something last night and decided to use StringRegExpReplace() for a config file, I never noticed that you cant just "overwrite" the file with the update so easily it required a few more pieces of code to work properly.
      Is this the simplest way (what I used) and while I searched for it and did not find it do we have or will we have a RegEx equivalent for _ReplaceStringInFile()?
      $sFile = FileRead(@ScriptDir & "\test.txt") $hFile = FileOpen(@ScriptDir & "\test.txt", 2) $sNewContent = StringRegExpReplace($sFile, "(test)", "new$1") FileWrite($hFile, $sNewContent) FileClose($hFile)  
    • Mecano
      By Mecano
      Hallo Members,
      I'm looking for a good regex to get the drive letter and the last two folders from a file path,
      If the path is to long for the label width then show drive +   ellipses and two last folders.
      Drive:\(ellipses)\folder\folder
      ex. D:\...\folder\folder
      and when the folder is in the root of the drive then show D:\Folder

      The test GUI
      #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.12.0 Author: Mecano Script Function: ELLIPSIS Long path: Drive:\...\Folder\Folder if root then Drive:\Folder #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here $sFile = "F:\Just a folder\in a another folder\and another\This-dir\And-this-dir" $EllipsisPath = StringRegExpReplace($sFile, '\w[a-zA-Z \\]+\\', '') ; <- This needs another regex ;no ellipsis needed, for testing purposes only $sUSB = "K:\Just a folder" $PathforUSB = StringRegExpReplace($sUSB, '\w[a-zA-Z \\]+\\', '') #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> $Form1 = GUICreate("Drive + Two last folders of path", 327, 236, 192, 124) $Button1 = GUICtrlCreateButton("Test label", 40, 168, 97, 33) $Label1 = GUICtrlCreateLabel("F:\...\This-dir\And-this-dir", 40, 12, 200, 40) ; <- Looks good but not dynamic GUICtrlSetColor($Label1, 32768) $Label2 = GUICtrlCreateLabel($sFile, 40, 40, 200, 40, $DT_END_ELLIPSIS) ; <- not the last two directorys GUICtrlSetColor($Label2, 16711680) $Label3 = GUICtrlCreateLabel("Var label1", 40, 72, 200, 40) GUICtrlSetColor($Label3, 16711680) $Label4 = GUICtrlCreateLabel("Var label", 40, 104, 200, 40) GUICtrlSetColor($Label4, 16711680) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 GUICtrlSetData($Label3, $EllipsisPath) ; $DT_END_ELLIPSIS <- works only on GUICtrlCreateLabel GUICtrlSetData($Label4, $PathforUSB) EndSwitch WEnd  
       
      Thanks in advance