Search code examples
stringtclspecial-characters

Tcl - How to replace ? with -


(You'd think this would be easy, but I'm stumped.)

I'm converting an iOS note to a text file, and the note contains "0." and "?" whenever there is a list or bullet.

This was a bulleted list
? item 20
? Item 21
? Item 22

I'm having so much problem replacing the "?"

I don't want to replace a legitimate question mark at the end of a sentence, but I want to replace the "?" bullets with "-" (preferably anywhere in the line, not just at the beginning)

I tried these searches - no luck

set line "? item 20"
set index_bullet [string first "(\s|\r|\n)(\?)" $line]
set index_bullet [string first "(!\w)(\?)" $line]
set index_bullet [string first ^\? $line]

This works, but it would match any question mark

set index_bullet [string first \? $line]

Does anyone know what I'm doing wrong? How do I find and replace only question mark bullets with a "-"?

Thank you very much in advance


Solution

  • If you're really wanting to replace a question mark where you've got a regular expression that describes the rule, the regsub command is the right way. (The string first command finds literal substrings only. The string match command uses globbing rules.) In this case, we'll use the -all option so that every instance is replaced:

    set line "? item 20"
    set replaced [regsub -all {(\s|^)\?(\s)} $line {\1-\2}]
    puts "'$line' --> '$replaced'"
    # Prints: '? item 20' --> '- item 20'
    

    The main tricks to using regular expressions in Tcl are, as much as possible, to keep REs and their replacements in braces so that the you can use Tcl metacharacters (e.g., backslash or square brackets) without having to fiddle around a lot.

    Also, \s by default will match a newline.