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条)

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算