包含斜杠和星号作为常量的正则表达式

I am using Golang and I am trying to determine which regex will work to match any string that starts with:

/*

It has been dificult to get it, I tried many ways (I didn't save them all to writte them here), but some of them are:

{/*}.*?
//*.*?
//\\*[A-Za-z0-9_-]*$

If you want to match the whole source text, the regex must start with ^ and end with $ (anchors).

To match / use just /. In some other host languages (e.g. Javascript or Perl) slashes are used as regex delimiters, so to use the slash as the content of regex, you would have to escape it with a backslash, but in go this is not needed.

To match * use \*. You can not use just * (as Volker proposed), because it is a quantifier, meaning 0 or more.

As you want to match the whole string (not just /*), the next part should be .* (any number of any chars).

If you want to catch the "rest" of string in a capturing group, surround this part with parentheses.

And the last step of complication: Usually after /* there are some spaces and only after them the fragment you actually want to catch. In such case:

  • start from \s* (optional sequence of white chars),
  • then put (.*).

So the final solution is: ^/\*\s*(.*)$

For a working example see https://regex101.com/r/80ORab/1

Edit

If you write your regex as a string, in double quotes, the backslash must be written twice.

You need to escape the * with a backslash: ^/\*. However, if you use normal quotation marks, you need to escape that backslash itself as well:

"^/\\*"

Alternatively, you can use a raw string literal, which does not need the escaping of the backslash:

`^/\*`

Playground link: https://play.golang.org/p/v5y9l8dTXRs