不要在正则表达式中的描述内容中获取字符串

时间:2016-02-16 20:25:22

标签: php regex

你好,这是我的字符串

/*
anything description
*/

Data1 = value1;

Other_Data = Other_Value;

/*
my other description
*/

Anything = Any_Answer;

/*

this is description and must not detect

Description_Data = Any_Value;

*/

现在我想使用正则表达式并获得类似的东西

Data1
Other_Data
Anything

value1
Other_Value
Any_Answer

在数组中,但我不希望正则表达式检测(描述框)中的任何内容

/* */
,如

Description_Data = Any_Value;

这是我的正则表达式

\h*(.*?)\h*[=]\h*(.*?)\h*[;]

我的问题是正则表达式获取所有的键和值,即使在描述和一些键中,在键之前获取所有描述之前的所有内容...我希望得到像这样的

Data1
Other_Data
Anything

value1
Other_Value
Any_Answer

问题是什么?

1 个答案:

答案 0 :(得分:2)

我认为键和值仅包含字母数字和下划线。

您可以使用SKIP-FAIL PCRE construct跳过说明,并且仅匹配

行开头的键=值对
(?m)\/\*[^*]*\*+([^\/*][^*]*\*+)*\/(*SKIP)(*F)|^\s*(\w+)\s*=\s*(\w+)

请参阅regex demo

正则表达式匹配:

  • \/\*[^*]*\*+([^\/*][^*]*\*+)*\/(*SKIP)(*F) - 匹配多行注释(此模式使用unroll-the-loop技术编写并且非常高效)并使正则表达式引擎丢弃匹配的文本并移动索引到这个匹配文本的末尾(因此,我们忽略了描述)
  • | - 或......
  • ^\s*(\w+)\s*=\s*(\w+) - ^匹配行的开头,然后匹配并捕获到第1组()一个或多个单词字符(使用{{ 1}}),然后只匹配零个或多个空格((\w+)),然后匹配\s*,再次匹配零个或多个空白符号,然后我们捕获到第2组( )一个或多个单词字符。

=是内联修饰符,您可以将它们写为(?sm)'~pattern-here~sm' DOTALL 修饰符,使s与换行符匹配。 . MULTILINE 修饰符,使m^匹配的开头和结尾,而不是整个字符串。

当键和值可以包含任何字符且值尾随边界为$ +换行符/字符串结尾时更复杂的情况的变体:

;

请参阅another demo

IDEONE demo

(?sm)\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/(*SKIP)(*F)|^\s*([^=\n]+?)\s*=\s*(.*?);\h*(?:$|\r?\n)

输出:

$re = '~/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(*SKIP)(*F)|^\s*([^=\n]+?)\s*=\s*(.*?);\h*(?:$|\r?\n)~sm'; 
$str = "/*\nanything description\n*/\n\nData1 = value1;\n\nOtherData<> = Other Value;\n\n/*\nmy other description\n*/\n\nAny thing = Any \nAnswer;\n\n/*\n\nthis is description and must not detect\n\nDescription_Data = Any_Value;\n\n*/"; 
preg_match_all($re, $str, $matches);
print_r($matches[1]);
print_r($matches[2]);

要同时忽略完整的单行注释(以Array ( [0] => Data1 [1] => OtherData<> [2] => Any thing ) Array ( [0] => value1 [1] => Other Value [2] => Any Answer ) #;开头的行),您可以添加//替代SKIP-FAIL部分:

^\h*(?:\/\/|[#;])[^\n]*

请参阅another regex demo(?sm)(?:^\h*(?:\/\/|[#;])[^\n]*|\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/)(*SKIP)(*F)|^\s*([^=\n]+?)\s*=\s*(.*?);\h*(?:$|\r?\n) 匹配行的开头(使用^\h*(?:\/\/|[#;])[^\n]*),然后匹配^//#,然后匹配换行符以外的零个或多个字符(如果您有Mac OS行结尾,请添加;