Regex match for new lines

。_饼干妹妹 提交于 2020-01-16 15:46:12

问题


I am trying to get the log statements in my code using java. I am using this regex:

Log\.[dD].*\);

Test data:

Log.d(TAG, "Construct product info");

test test test test 

Log.d(TAG, "Loading Product Id: %d, Version: %s",
    productInfo.getProductId(),
    productInfo.getProductVersion());

test test test test 

Log.d(TAG, "Loading Product Id: " +
    ProductId + "Version:" +
    Version);

test test test test

for some reason, regex is only picking up 1st line which is

Log.d(TAG, "Construct product info");

Correct output should be:

Log.d(TAG, "Construct product info");

Log.d(TAG, "Loading Product Id: %d, Version: %s",
    productInfo.getProductId(),
    productInfo.getProductVersion());

Log.d(TAG, "Loading Product Id: " +
    ProductId + "Version:" +
    Version);

https://regex101.com/r/OCl9dy/3

If I am not mistaken, regex should return all Log.[dD] statements that ends with );

Please let me know why it does not pick up others and how to fix this.

thanks


回答1:


This regex should work:

Log\.[dD][\s\S]*?\);

The two mistakes you made were:

  • . does not match line endings. You should use something similar to [\s\S], which matches everything.
  • You need to match lazily, stop matching at the first ) you see. So write *? instead of *.

Note that the regex won't work for things like Log.d(TAG, "Construct (product); info"); because the first ); is not the end of the method call. To match these, I suggest you write/use a parser.

Demo



来源:https://stackoverflow.com/questions/51060391/regex-match-for-new-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!