dou44364983 2018-07-04 05:22
浏览 216
已采纳

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

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_-]*$
  • 写回答

2条回答 默认 最新

  • drbae3964 2018-07-04 06:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型