Jump to content
Chimp

how to enclose strings in quotation marks using a regular expression?

Recommended Posts

Hello
if I have a string like in the example below,
is there a regular expression that can surround any "string" (and only strings) within quotes?.
The whole input string is a "constructor" to populate an array so even if an element contains more words (a phrase) it should be considered as a single word (Elton John should be considered a single word and as that quoted as "Elton John")
for example
the following string

[[Elton John,Peter,Sally,123],[1 one 1,2,3,4 four 4]]

should be transformed to this other string

[["Elton John","Peter","Sally",123],["1 one 1",2,3,"4 four 4"]]

Thanks for your help

Here a small script to use as "guinea pig"

#include <Array.au3>

Local $aArray = [["Elton John", "Peter", "Sally", 123],["one 1", 2, 3, "4 four 4"]]
MsgBox(0, "Result", _Array2Json($aArray))

Func _Array2Json($aArray)
    If (Not IsArray($aArray)) Or (UBound($aArray, 0) > 2) Then Return SetError(1, 0, '')
    Local $sOpening, $sClosing
    If UBound($aArray, 0) = 1 Then
        $sOpening = '['
        $sClosing = ']'
    Else
        $sOpening = '[['
        $sClosing = ']]'
    EndIf

    $sOutpt = $sOpening & _ArrayToString($aArray, ",", -1, -1, "],[") & $sClosing

    ;  $sOutpt = ???? how to quote strings ????

    Return $sOutpt
EndFunc   ;==>_Array2Json

 

Edited by Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites

Something like this should do it. It is a updated version of _ArrayToString() - see the comments in the UDF:

#include <Array.au3>

Local $aArray = [["Elton John", "Peter", "Sally", 123], ["one 1", 2, 3, "4 four 4"]]
MsgBox(0, "Result", _Array2Json($aArray))

Func _Array2Json($aArray)
    If (Not IsArray($aArray)) Or (UBound($aArray, 0) > 2) Then Return SetError(1, 0, '')
    Local $sOpening, $sClosing
    If UBound($aArray, 0) = 1 Then
        $sOpening = '['
        $sClosing = ']'
    Else
        $sOpening = '[['
        $sClosing = ']]'
    EndIf


    $sOutpt = $sOpening & _ArrayToString_ex($aArray, ",", -1, -1, "],[") & $sClosing

    ;  $sOutpt = ???? how to quote strings ????

    Return $sOutpt
EndFunc   ;==>_Array2Json

Func _ArrayToString_ex(Const ByRef $aArray, $sDelim_Col = "|", $iStart_Row = -1, $iEnd_Row = -1, $sDelim_Row = @CRLF, $iStart_Col = -1, $iEnd_Col = -1)
    If $sDelim_Col = Default Then $sDelim_Col = "|"
    If $sDelim_Row = Default Then $sDelim_Row = @CRLF
    If $iStart_Row = Default Then $iStart_Row = -1
    If $iEnd_Row = Default Then $iEnd_Row = -1
    If $iStart_Col = Default Then $iStart_Col = -1
    If $iEnd_Col = Default Then $iEnd_Col = -1
    If Not IsArray($aArray) Then Return SetError(1, 0, -1)
    Local $iDim_1 = UBound($aArray, $UBOUND_ROWS) - 1
    If $iStart_Row = -1 Then $iStart_Row = 0
    If $iEnd_Row = -1 Then $iEnd_Row = $iDim_1
    If $iStart_Row < -1 Or $iEnd_Row < -1 Then Return SetError(3, 0, -1)
    If $iStart_Row > $iDim_1 Or $iEnd_Row > $iDim_1 Then Return SetError(3, 0, "")
    If $iStart_Row > $iEnd_Row Then Return SetError(4, 0, -1)
    Local $sRet = ""
    Switch UBound($aArray, $UBOUND_DIMENSIONS)
        Case 1
            For $i = $iStart_Row To $iEnd_Row
                ; Added this logic
                If IsString($aArray[$i]) Then
                    $sRet &= '"' & $aArray[$i] & '"' & $sDelim_Col
                Else
                    $sRet &= $aArray[$i] & $sDelim_Col
                EndIf
            Next
            Return StringTrimRight($sRet, StringLen($sDelim_Col))
        Case 2
            Local $iDim_2 = UBound($aArray, $UBOUND_COLUMNS) - 1
            If $iStart_Col = -1 Then $iStart_Col = 0
            If $iEnd_Col = -1 Then $iEnd_Col = $iDim_2
            If $iStart_Col < -1 Or $iEnd_Col < -1 Then Return SetError(5, 0, -1)
            If $iStart_Col > $iDim_2 Or $iEnd_Col > $iDim_2 Then Return SetError(5, 0, -1)
            If $iStart_Col > $iEnd_Col Then Return SetError(6, 0, -1)
            For $i = $iStart_Row To $iEnd_Row
                For $j = $iStart_Col To $iEnd_Col
                    ; Added this logic
                    If IsString($aArray[$i][$j]) Then
                        $sRet &= '"' & $aArray[$i][$j] & '"' & $sDelim_Col
                    Else
                        $sRet &= $aArray[$i][$j] & $sDelim_Col
                    EndIf
                Next
                $sRet = StringTrimRight($sRet, StringLen($sDelim_Col)) & $sDelim_Row
            Next
            Return StringTrimRight($sRet, StringLen($sDelim_Row))
        Case Else
            Return SetError(2, 0, -1)
    EndSwitch
    Return 1

EndFunc   ;==>_ArrayToString_ex

Jos

Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

Thanks @Jos,
it works, you have "exploited" the internal scan of the _ArrayToString () function to search for array elements that contain strings, nice, thank you :).


It would also be interesting to have a solution that uses regexp instead of looping all the elements of the array ((even if _ArrayToString does it already)
Thanks


small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites

.... it would seem that this solution also works.  (I had no doubts of course :P).
very beautiful!

Thanks a lot @mikell


small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites

OTOH if you want to match JSON definitions of its internal structure you can do so explicitely:

Local $sIn = "{[[Elton John, Bonnie & Clyde, Sally, 123],[one 1, 2, 3, 4 four 4]], abc, [7,{a,b,[c,d,3]}]}"
_String2Json($sIn)
MsgBox(0, "Result", $sIn)

Func _String2Json(ByRef $s)
    $s = StringRegExpReplace($s, _
        '(?x)' & _
        '(?(DEFINE) (?<table>   \{ \h* (?: (?&element) (?: \h* , \h* (?&element) )* \h* \} ) ) )' & _
        '(?(DEFINE) (?<array>   \[ \h* (?: (?&element) (?: \h* , \h* (?&element) )* \h* \] ) ) )' & _
        '(?(DEFINE) (?<element> (?&table) | (?&array) | (?&number) | (?&string) ) )' & _
        '(?(DEFINE) (?<number>  [-+]? \d+ (?: \.\d+ )? (?: [Ee] [-+]? \d+ )? ) )' & _
        '(?(DEFINE) (?<string>  \b \w* [^\[\],]*[[:alpha:]_]+ [\w\h]* ) )' & _
        '( (?&string) )', _
        '"$6"')
EndFunc   ;==>_Array2Json

Of course, once that invalid input string is reformatted to correctly enclose strings inside double quotes, things are easier to handle.

Edited by jchd

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)

Share this post


Link to post
Share on other sites

I haven't used *SKIP or *FAIL before. Thank you for an example with these! TIL


All my code provided is Public Domain... but it may not work. ;) Use it, change it, break it, whatever you want.

Spoiler

My Humble Contributions:
Personal Function Documentation - A personal HelpFile for your functions
Acro.au3 UDF - Automating Acrobat Pro
ToDo Finder - Find #ToDo: lines in your scripts

Share this post


Link to post
Share on other sites

Yeah, backtracking control verbs are powerful but require real care if you don't want to get bitten.


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)

Share this post


Link to post
Share on other sites
22 minutes ago, jchd said:

OTOH if you want to match JSON definitions of its internal structure you can do so explicitely

It's obviously much more robust and clean  :)

... reason why I very carefully mentioned the initial requirements :D

Share this post


Link to post
Share on other sites

I wrote that quite quickly and I suppose there are holes left around.

For instance, the definition of number isn't fully correct as that would match inside strings!  That's because recursion inside the nested names don't need to be matched: if you request only numbers, for instance, nothing forces this part to be an element, itself part of an array or table.

Also, multi-dimensional tables (arrays) need to have the same number of entries for dimensions > 1, which is hard to check that way.

Nonetheless the use of named subroutines, as in (?(DEFINE) (?<object> ...) ... (... (?&object) ... ) can be very handy at times.


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)

Share this post


Link to post
Share on other sites
4 minutes ago, jchd said:

I suppose there are holes left around.

There are... For instance, one [:alpha:] is needed to validate a string so "4_4" fails
Named subroutines are very useful indeed. I rarely use them because it involves a complicated pattern... and because of my laziness :>

 

Share this post


Link to post
Share on other sites

Fixed, but there must be more (left as exercise to the reader, as they say).

Not enough time to dig further: I still have a significant number of electronic boards to repair and ship tomorrow.  I also need to make progress to finish a hardware/software prototype of a high-precision driver board delivering controlled bursts of extremelly short pulses with ultra-low (sub ns) jitter to medium-power laser diodes.  Late Sunday work.


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)

Share this post


Link to post
Share on other sites

This description looks like klingon for me :blink:
...
My previous try could be done more accurate anyway

Local $s = "{[[Elton John, Bonnie & Clyde, Sally, 123],[one 1, 2&, 3, 4_#4]], abc, [7,{a,b,[c,d,3]}]}"

$res = StringRegExpReplace($s, '\h*\d*\h*(?=[,\{\[\]])(*SKIP)(*F)|\h*([^\{\}\[\],]+)\h*', '"$1"')

Msgbox(0,"", $res)

:)

Share this post


Link to post
Share on other sites

Klingon too 🙂

Geez, I just realize that +- signs got lost in translation, just like scientific notation!


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)

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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By cruisepandey
      Hi, 
      I have a string like this : 
      Global $Msga = "urrent directory is /send.  (Submission of file with log number 29381077284 is confirmed)";
      I want to extract the number 29381077284  from the string. I did StringSplit to split based on "(" and then use space to reach there, But it's not a good choice. 
      Can anyone help me with regular expression to find the number from String using AutoIT. TIA
    • By genius257
      Inspired by PHP's preg_split.
      Split string by a regular expression.
      Also supports the same flags as the PHP equivalent.
      v1.0.1
       
      Example:
      #include "StringRegExpSplit.au3" StringRegExpSplit('splitCamelCaseWords', '(?<=\w)(?=[A-Z])') ; ['split', 'Camel', 'Case', 'Words']  
    • By nend
      This is a program that I made to help my self learn better regular expressions.
      There are a lot of other programs/website with the similar functions.
      But the main advantage of this program is that you don't have to click a button after every changes.
      The program detected changes and react on it.
      Function:
      Match Match of arrays Match and replace Load source data from website Load source data from a website with GET/POST Load text data from file Clear fields Export and Import settings (you can finish the expression a other time, just export/import it) Cheat sheet Generate AutoIt code example code The source code is not difficult and I think most user will understand it.
      In the zip file there is a export files (reg back example), you can drag and drop this files on the gui to import it.
      Download Regex Toolkit Regex toolkit.zip  (Sourcode, example and compiled exe file)
      EDIT: Updated to version V1.2.0
      Changes are:
      Expand and collapse of the cheat sheet (Thanks to Melba23 for the Guiextender UDF) Usefull regular expressions websites links included in the program Text data update time EDIT: Updated to version V1.3.0
      Changes are:
       Automatic generate AutoIt code  Icons on the tab  Few minor bug fixes EDIT: Updated to version V1.4.0
      Changes are:
      Link to AutoIt regex helpfile If the regular expression has a error than the text becomes red Option Offset with Match and array of Matches Option Count with Match and replace Some small minor bug fixed EDIT: Updated to version V1.4.1
      Changes are:
      Small bug in "create AutoIt" code fixed EDIT: Updated to version V1.4.2
      Changes are:
      Small bug in "create AutoIt" code fixed Bug with website data  fixed 
      Regex toolkit.zip  (Sourcode, example and compiled exe file)
    • By lee321987
      Hello, I'm trying to match the second to last line of this:
      foo C:\ foobar foobar x C:\temp\dir Last line with chars Here's my code:
      $test = 'foo' & @CRLF $test &= 'C:\' & @CRLF $test &= 'foobar' & @CRLF $test &= 'hello' & @CRLF $test &= 'C:\temp\dir' & @CRLF $test &= 'Last line with chars' & @CRLF $test &= @CRLF $test &= @CRLF $result = StringRegExp($test, '(?m)^C:\\.*$Last.*') MsgBox(0, '', $result) I'm trying to match line "C:\temp\dir".  Anyone have any ideas?
    • By therks
      I'm looking for a regex genius, cus I'm stumped when it comes to assertions.
      So what I have now, is this regular expression: ([^|=]+)=([^|]+)
      It takes a string (user input) of keys=values separated by pipes (ie: "param=value|param=value") and splits them into an array.
      Example:
      $vParamData = 'example=value|fruit=apple|phrase=Hello world' $aRegEx = StringRegExp($vParamData, '([^|=]+)=([^|]+)', 3) ; Result ; [0] => example ; [1] => value ; [2] => fruit ; [3] => apple ; [4] => phrase ; [5] => Hello world So that's working fine, but I'm wondering if there's also a way I could have this capture escaped pipes instead of splitting by them.
      ie:
      $vParamData = 'pipe test=this \| is a pipe|example=value' $aRegEx = StringRegExp($vParamData, '([^|=]+)=([^|]+)', 3) ; I'm getting this: ; [0] => pipe test ; [1] => this \ ; [2] => example ; [3] => value ; But I'd like a result like this: ; [0] => pipe test ; [1] => this \| is a pipe ; [2] => example ; [3] => value Is there some pattern that would accomplish this, or am I better off parsing it some other way?
×
×
  • Create New...