如何捕捉多个字母

时间:2014-03-16 14:44:28

标签: regex

/**
 * SOMETHING BLABLABLA
 * Date: 3/16/14
 * Time: 8:29 PM
 */

我希望匹配从/ **到* /

的任何内容

我可以将/ **与第一个*匹配:

/\*\*([^\*]*)\*

但我不知道如何取消最后两个字母的匹配。

2 个答案:

答案 0 :(得分:3)

您可以使用:

/(?:^\s*\/\*\*)(.*)(?:^\s*\*\/)/ms

See it work

或Debuggex版本:

Regular expression visualization

Debuggex Demo

通过' unmatch'我认为你的意思是有一个未包含在比赛组中的组。您使用以(?:regex)开头的非捕获组来执行此操作。

完整的解释是:

/(?:^\s*\/\*\*)(.*)(?:\s*\*\/)/ms
(?:^\s*\/\*\*) Non-capturing group
    ^ assert position at start of a line
    \s* match any white space character [\r\n\t\f ]
    Quantifier: Between zero and unlimited times, as many times as possible, 
    giving back as needed [greedy]
    \/ matches the character / literally
    \* matches the character * literally
    \* matches the character * literally
1st Capturing group (.*)
    .* matches any character
    Quantifier: Between zero and unlimited times, as many times as possible, 
    giving back as needed [greedy]
(?:\s*\*\/) Non-capturing group
    \s* match any white space character [\r\n\t\f ]
    Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    \* matches the character * literally
    \/ matches the character / literally
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
s modifier: single line. Dot matches newline characters

如果你想匹配:

/**
 * SOMETHING BLABLABLA
 * Date: 3/16/14
 * Time: 8:29 PM*/
                ^ comment terminator 

只需将最终非捕获组中的锚点移除为(?:\s*\*\/)

即可

对于Sublime,您需要设置标志ms。使用:

(?ms)(?:^\s*\/\*\*)(.*)(?:^\s*\*\/)
^^^^ This part sets the flags for Boost regex engine...

答案 1 :(得分:2)

试试这个,这需要dot-matches-all:

/\*\*.*?\*/

或者,这会捕获每行上的所有星号后文本......排序:

/\*\*(?:\s+\* ([^\r\n]+))+\s+\*/

Regular expression visualization

Debuggex Demo

实际上它只捕获最后一行,但看起来确实更接近。