1

这是我在stackoverflow上的第一篇文章,所以请对我温柔...

我仍在学习正则表达式——主要是因为我终于发现了它们的用处,这部分是通过使用 Sublime Text 2。所以这是 Perl 正则表达式(我相信)

我已经在这个网站和其他网站上搜索过了,但我现在真的被困住了。也许我正在尝试做一些无法做到的事情

我想找到一个正则表达式(模式),它可以让我找到包含给定变量或方法调用的函数、方法或过程等。

我已经尝试了许多表达方式,它们似乎得到了一部分但不是全部。特别是在 Javascript 中搜索时,我选择了多个函数声明,而不是最接近我正在寻找的调用/变量的声明。

例如:我正在寻找调用我学到的方法 save data() 的函数,从这个我可以使用 (?s) 切换的优秀网站。包括换行符

function.*(?=(?s).*?savedata\(\))

但是,这将找到 word 函数的第一个实例,然后是包含 savedata() 在内的所有文本

如果有多个过程,那么它将从下一个函数开始并重复,直到再次到达 savedata()

function(?s).*?savedata\(\) does something similar

我曾尝试通过使用以下方法要求它忽略第二个功能(我相信):

function(?s).*?(?:(?!function).*?)*savedata\(\)

但这不起作用。

我已经进行了一些向前看和向后看的调查,但要么我做错了(很有可能),要么他们不是正确的事情。

总而言之(我猜),我如何从给定的单词倒退到最近出现的不同单词。

目前我正在使用它来搜索一些 javascript 文件以尝试理解结构/调用等,但最终我希望在 c# 文件和一些 vb.net 文件上使用

提前谢谢了

感谢您的快速响应,很抱歉没有添加示例代码块 - 我现在将执行此操作(已修改但仍足以显示问题)

如果我有一个简单的 javascript 块,如下所示:

    function a_CellClickHandler(gridName, cellId, button){
        var stuffhappenshere;
        var and here;
        if(something or other){
            if (anothertest) {

                event.returnValue=false;
                event.cancelBubble=true;
                return true; 
            }
            else{
                event.returnValue=false;
                event.cancelBubble=true;
                return true;
            }
        } 
    }

    function a_DblClickHandler(gridName, cellId){
        var userRow = rowfromsomewhere;
        var userCell = cellfromsomewhereelse;
        //this will need to save the local data before allowing any inserts to ensure that they are inserted in the correct place
        if (checkforarangeofthings){
            if (differenttest) {
                InsSeqNum = insertnumbervalue;
                InsRowID = arow.getValue()
                blnWasInsert = true;
                blnWasDoubleClick = true;
                SaveData();      
            }
        }
    }

对此运行正则表达式 - 包括被识别为应该工作的第二个,Sublime Text 2 将选择从第一个函数到 SaveData() 的所有内容

在这种情况下,我希望能够只访问 dblClickHandler - 而不是两者兼而有之。

希望这个代码片段会增加一些清晰度,并且很抱歉最初没有发布,因为我希望标准代码文件就足够了。

4

1 回答 1

0

此正则表达式将查找包含 SaveData 方法的每个 Javascript 函数:

(?<=[\r\n])([\t ]*+)function[^\r\n]*+[\r\n]++(?:(?!\1\})[^\r\n]*+[\r\n]++)*?[^\r\n]*?\bSaveData\(\)

它将匹配函数中的所有行,包括包含 SaveData 方法的第一行。

警告:

  • 源代码必须具有格式良好的缩进才能工作,因为正则表达式使用匹配的缩进来检测函数的结尾。
  • 如果函数从文件的第一行开始,它将不匹配。

解释:

(?<=[\r\n])                      Start at the beginning of a line
([\t ]*+)                        Capture the indentation of that line in Capture Group 1
function[^\r\n]*+[\r\n]++        Match the rest of the declaration line of the function
(?:(?!\1\})[^\r\n]*+[\r\n]++)*?  Match more lines (lazily) which are not the last line of the function, until: 
[^\r\n]*?\bSaveData\(\)          Match the first line of the function containing the SaveData method call

注意: and*+++所有格量词,仅用于加快执行速度。

编辑: 修复了正则表达式的两个小问题。
编辑: 修复了正则表达式的另一个小问题。

于 2013-01-27T01:15:52.240 回答