Search code examples
tclregexp-replace

Search backslach in tcl using regexp


How to search backslash "\" in tcl using regexp. I tried following

regexp {\\} "b\a"
regexp {\\\\} "b\a"

I want to search text between "." and "\.". How to do this? Eg: abcd.efg\.hij => efg , for this I tried this:

regexp {\.[a-z]*\\.} "abcd.efg\.hij" X

Solution

  • When single backslash is used in double quotes, then it has no special meaning at all. It should be escaped.

    % set input "abcd.efg\.hij"; # Check the return value, it does not have backslash in it
    abcd.efg.hij
    %
    % set user "din\esh"; # Check the return value
    dinesh
    %
    % set input "abcd.efg\\.hij"; # Escaped the backslash. Check the return value
    abcd.efg\.hij
    %
    % set input {abcd.efg\.hij}; # Or you have to brace the string
    abcd.efg\.hij
    %
    

    So, your regexp should be updated as ,

    % regexp "\\\\" "b\\a"
    1
    % regexp {\\} "b\\a"
    1
    % regexp {\\} {b\a}
    1
    % regexp {\\} {b\\a}
    1
    %
    

    To extract the required data,

    % set input {abcd.efg\.hij}
    abcd.efg\.hij
    %  regexp {\.(.*)?\\} $input ignore match
    1
    % set match
    efg