Sublime Forum

Regex keybind, how to match literal asterisk?

#1

[code]{
“keys”: “enter”], “command”: “insert_snippet”,
“args”:
{
“contents”: “\n*$0b”
},
“context”:

    { "key": "preceding_text", "operator": "regex_contains", "operand": "\\*", "match_all": true }
]

}[/code]
Why does that keybind match:

* Whatever|

with the pipe being the cursor position.

I’m guessing because it’s translating that to: "\" (e.g. 0 or more backslashes)*? If so, how do you match a literal asterisk? Using one backslash causes a parse error and a single or double asterisk doesn’t work.

0 Likes

#2

What if you changed the “\" to "\$”? I’m not sure how “preceding_text” works.
To be 100% sure you’re capturing an asterisk character, you could use “*]”.

0 Likes

#3

Bah, yeah you’re right. For whatever reason I thought preceding_text would only match if it was directly preceding the cursor. So "\"* would only match "|"* and not if there was just an asterisk anywhere behind the cursor. Thanks.

0 Likes

#4

As adzenith suggested, “]$" is what you want: a single asterisk just before the cursor. Escaping is a little tricky, as you have to escape the JSON encoding and the regex encoding, which generally means just doubling the number of backslashes you think you need, so another option is "\\$”

0 Likes

#5

Aye, my issue was more the dollar sign than it was the asterisk. I just didn’t realize that it was matching against everything before and after the cursor. I thought if the match wasn’t attached to the cursor it wouldn’t match. Also “\*” seems to match an asterisk, don’t think 4 is needed. Thanks again.

0 Likes