dtfpznrbn503027700 2015-02-07 12:34
浏览 32

使用Regex在文件中查找多次出现的字符串 - PHP

I'm new to using Regex and was wondering if someone could point me in the right direction.

My problem is as follows:

I need to pattern match an entire file to determine if code meets a rule. Local Variable Could Be Final. Essentially if the following code is within a file, I will need to check if the variable is assigned again. If not generate a warning to suggest an improvement.

public class Bar {
public void foo () {
    String txtA = "a"; // if txtA will not be assigned again it is better to do this:
    final String txtB = "b";
    }
}

I of course have to do this for many other examples but I've not been taught Regex and it's not part of my course, if you can suggest a pattern for this or provide a link to help me learn, I'd very much appreciate it.

Ideally I'd like to do this in one go, I could of course generate a set of variable occurrences and "scan" the file again to see if these appear < 2 times. But Regex is lightning fast, and I want to approach this in such a way that I can have one method and I'll simply pass in the pattern + string for matching.

I've had a go already and I can find multiple occurrences but if another variable is between two instances my Regex won't pick them up..

It's close, but I feel will not work in pretty much every scenario bar one.

Regex: (\s*txtA\s*=\s*.*){2,}

public class Bar {
public void foo () {
    String txtA = "a";       // matches
           txtA =  "ab";     // matches
    String txtB =  "xxx";    // breaks the match
           txtA =  "abc";    // doesn't match, but should.
}

}

If the above is the wrong way to approach this and you're aware of a more efficient way, perhaps some PHP Library, please do suggest.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
    • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
    • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)