简体   繁体   English

多行正则表达式匹配问题

[英]Multiline Regex Matching Issue

I have the following string that I am trying to match via regex: 我想通过正则表达式匹配以下字符串:

;IF TEST_DATE <= 200112 THEN E>=90 AND S>=90
 OR P = "25" ENDIF
IF TEST_DATE >= 200201 AND TEST_DATE < 200407 THEN E>=89
AND S>=90 OR P = "25" ENDIF

I am using the following regex in an attempt to match from the semicolon (intended to be a comment) until the first ENDIF: 我正在使用以下正则表达式,以尝试从分号(打算作为注释)到第一个ENDIF进行匹配:

;\s*IF (\d|\D)+ ENDIF

Unfortunately, this pattern matches all the way until the second ENDIF. 不幸的是,该模式一直匹配到第二个ENDIF。 I've tried various solutions using the Java Pattern.DOTALL, as well as the (?s) flag, with no luck. 我已经尝试过使用Java Pattern.DOTALL以及(?s)标志进行各种解决方案,但是没有运气。

You are using greedy quantifier, due to which your pattern (\\d|\\D) matches everything till it finds the last ENDIF . 您正在使用greedy量词,因此您的模式(\\d|\\D)匹配所有内容,直到找到最后一个ENDIF为止。

You need to use reluctant quantifier - +? 您需要使用reluctant quantifier - +? if you want your regex to stop matching at the first ENDIF : - 如果您希望正则表达式在第一个ENDIF处停止匹配:-

;\s*IF (\d|\D)+? ENDIF

使用非贪婪的限定词。

;\s*IF (\d|\D)*? ENDIF

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

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