简体   繁体   English

正则表达式匹配新行

[英]Regex match for new lines

I am trying to get the log statements in my code using java. 我正在尝试使用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 https://regex101.com/r/OCl9dy/3

If I am not mistaken, regex should return all Log.[dD] statements that ends with ); 如果我没记错的话,正则表达式应该返回所有以)结尾的Log。[dD]语句;

Please let me know why it does not pick up others and how to fix this. 请让我知道为什么它没有收到别人以及如何解决此问题。

thanks 谢谢

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. 您应该使用类似于[\\s\\S] ,该名称应与所有内容匹配。
  • 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"); 请注意,正则表达式不适用于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 演示版

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

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