简体   繁体   English

Matlab中多行注释的正则表达式

[英]Regular expression for multiline commentary in Matlab

I try to write a regexp that would match this pattern: 我尝试编写一个与该模式匹配的正则表达式:

%{
...
...
%}

It should also match: 它也应该匹配:

sth   %{
...
...
  %}

or 要么

%{
something%}
%}again something
%}

but not: 但不是:

%{something
...
%}

or 要么

%{
...
%}something

or 要么

%{
...
something%}

So it matches everything between a line with whatever character followed by %{ and a line with only %} (see multiline comment Matlab : https://fr.mathworks.com/help/matlab/matlab_prog/comments.html ) 因此,它匹配带有任意字符后跟%{的行和仅包含%}的行之间的所有内容(请参见多行注释Matlab: https : //fr.mathworks.com/help/matlab/matlab_prog/comments.html

I tried this : 我尝试了这个:

     ^.*%\{\n(^((?!%\}).)*\n)*(\s)*%\}\n

It works well to find the block, but for example, it doesn't match: 查找块效果很好,但是例如,它不匹配:

%{
%}something
...
%}

Do you have any ideas ? 你有什么想法 ?

You may use 您可以使用

^.*%\{(?:\n(?!.*%\{).*)*\n\s*%\}$

See the regex demo . 参见regex演示 Use it with a multiline modifier. 与多行修饰符一起使用。

If your regex engine is Java, you may use \\R to match any line break and \\h instead of \\s to match any horizontal whitespace: 如果您的正则表达式引擎是Java,则可以使用\\R来匹配任何换行符,并使用\\h而不是\\s来匹配任何水平空格:

^.*%\{(?:\R(?!.*%\{).*)*\R\h*%\}$

See this regex demo . 请参阅此正则表达式演示

Details 细节

  • ^ - start of a line ^ -一行的开始
  • .* - any 0+ chars other than line break chars as many as possible .* -尽可能多的0+个除换行符以外的字符
  • %\\{ - a %{ substring %\\{ -一个%{子字符串
  • (?:\\n(?!.*%\\{).*)* - 0 or more sequences of (?:\\n(?!.*%\\{).*)* -0个或多个序列
    • \\n(?!.*%\\{) - a newline not followed with %{ anywhere on the current line \\n(?!.*%\\{) -当前行中任何地方都没有换行符%{
    • .* - any 0+ chars other than line break chars as many as possible .* -尽可能多的0+个除换行符以外的字符
  • \\n - a newline \\n换行符
  • \\s* - 0+ whitespaces \\s* -0+空格
  • %\\} - a %} substring %\\} -一个%}子字符串
  • $ - end of line. $ -行尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM