简体   繁体   English

如何在txt文件中返回方法的内容

[英]How return contents of method in txt file

I'm trying to write a regular expression to return the method contents between method name and the following method name.我正在尝试编写一个正则表达式来返回方法名称和以下方法名称之间的方法内容。 I'll further parse that for info I'm extracting.我将进一步解析我正在提取的信息。 How do I do that?我怎么做? So far I have it working to get the info from the method name on, but don't know how to get it to stop at the following method name.到目前为止,我已经开始从方法名称中获取信息,但不知道如何让它停止在以下方法名称处。 Any other ideas would be appreciated.任何其他想法将不胜感激。

This returns the line s that match string method name (but I want entire method):这将返回与字符串方法名称匹配行(但我想要整个方法):

$contents = Get-Content $codePath | Select-String -Pattern "$methodNameToReturn.*" -AllMatches

This is where I'm trying to get it to end the string returned at the following method, but it's not finding anything:这是我试图让它结束在以下方法返回的字符串的地方,但它没有找到任何东西:

Get-MethodContents -codePath $File[0] -methodNameToReturn "GetStatusFromCode" -followingMethodName "SkipPage"

Function Get-MethodContents{
[cmdletbinding()]
Param ( [string]$codePath, [string]$methodNameToReturn, [string]$followingMethodName)
Process
{
    $contents = ""
    Write-Host "In GetMethodContents method File:$codePath method:$methodNameToReturn followingMethod:$followingMethodName"  -ForegroundColor Green
    #Switch -regex (Get-Content -Path $codePath)
    #{
    #'^(.*)/s'{$contents=$switch.current}
    #}
    $contents = Get-Content $codePath | Select-String -Pattern "($methodNameToReturn.*$followingMethodName)" -AllMatches
    Write-Host "File Contents Found: $contents" -ForegroundColor Cyan
}#End of Process
}#End of Function

Here's example code trying to match (what's important is I get what's inside GetStatusFromCode method to parse further):这是尝试匹配的示例代码(重要的是我得到了 GetStatusFromCode 方法中的内容以进一步解析):

...
bool ClassName::GetStatusFromCode(                DWORD              errorCode,
                                                  TCHAR              *errorStr,
                                                  DWORD              &outError,
                                                  COM_ERROR_SEVERITY &outSeverity,
                                                  TCHAR              *outDevStr)
{

    m_bRestart = TRUE;

    BYTE MinorCode = 0;

    // Get and check width
    DWORD dwLength = 0;
    BYTE buff[ 2 ] = {0};
    
    //
    if ( chcusb_getInfo( (WORD)kPINFTAG_SVCINFO, buff,  &dwLength ) == FALSE ) 
    {
        // Error
    }

    MinorCode = buff[1];


    switch( errorCode ) 
    {
        //case kRESULT_NOERROR:                     
        case kRESULT_MEMFULLERR:
            //code
            _sprintf(outDevStr, _T("8000 - (Comm Err)"), errStr);
            outError = errVar;
            break;

        case kRESULT_USBNOTFOUND:                   
            //code
            _sprintf(outDevStr, _T("8001 - (Comm 1 Err)"), errStr);
            outError = errVar;
            break;
        default:
            // Maybe communication error
            
            break;
    }

    m_dwErrorCode = outError;

    if ( m_bRestart == TRUE )
    {
        return true;
    }
    else
    {
        return false;
    }
}


////////////////////////////////////////
//
// METHOD NAME:     SkipPage
//
////////////////////////////////////////
bool ClassName::SkipPage( GUID JobID, DWORD dwPageNum )
...

This is where I've looked for more info:这是我寻找更多信息的地方:

match characters across multiple lines 匹配多行字符

extract string in text file 提取文本文件中的字符串

My question is how do I extract contents of that method name entirely?我的问题是如何完全提取该方法名称的内容? I don't care if it includes the followingMethodName, but it needs to get multiple lines until the end text of the method of interest, methodNameToReturn.我不在乎它是否包含以下MethodName,但它需要获取多行,直到感兴趣的方法的结束文本methodNameToReturn。 Yes, I know this is weird to want to do, but it's what is being asked for.是的,我知道这样做很奇怪,但这就是我们所要求的。 This is PowerShell 5.1.这是 PowerShell 5.1。

Edit: I exited the powershell file and it looks like it's finding the files still, but now it's not finding anything with either regex.编辑:我退出了 powershell 文件,看起来它仍在查找文件,但现在它没有找到任何正则表达式。

First, to match multiple lines, you must get the "raw" content of the file.首先,要匹配多行,您必须获取文件的“原始”内容。 Get-Content returns a list of strings by default, but -Raw gives you a single string that you can match through: Get-Content默认返回一个字符串列表,但-Raw为您提供一个可以匹配的字符串:

$contents = Get-Content $codePath -Raw

Then to regex across multiple lines, you must capture line-ending characters.然后要跨多行进行正则表达式,您必须捕获行尾字符。 .* excludes line endings, so I use either [\s\S]* for this on windows files instead. .*不包括行尾,所以我在 windows 文件上使用[\s\S]*来代替。 I'm also adding Classname:: from your example because it seems like a good place to start/end:我还从您的示例中添加Classname:: ,因为它似乎是一个开始/结束的好地方:

# -match usually returns true/false, so suppress
$null = $contents -match "(Classname::$methodNameToReturn[\s\S]*)Classname::$followingMethodName"

# Return the contents of the first capture group () as a single string
$Matches.Item(1)

More info about -Match有关-Match 的更多信息

Shy of writing a fullblown C++ parser, one useful heuristic would be to consume the method body until you reach a closing } that corresponds to the opening { - the nice thing about this approach is that PowerShell's regex operators can find them for you!不愿编写成熟的 C++ 解析器,一个有用的启发式方法是使用方法主体,直到到达对应于开头{的关闭} - 这种方法的好处是PowerShell 的正则表达式运算符可以为您找到它们!

The .NET regex engine supports something called balancing groups , which allows us to keep track of how many opening brackets we've encountered, and decrement the counter every time we encounter a corresponding closing bracket: .NET 正则表达式引擎支持称为平衡组的东西,它允许我们跟踪我们遇到了多少个左括号,并在每次遇到相应的右括号时递减计数器:

Select-String -Path $codePath -Pattern "(?s)$methodNameToReturn\s*\(.*\)\s*\{(?:[^{}]|(?<bracket>\{)|(?<-bracket>\}))+(?(bracket)(?!))\}"

Surely you can do it with Select-String as well but the regex could be just:当然,您也可以使用 Select-String 来做到这一点,但正则表达式可能只是:

$contents = [regex]::Match($codePath,"(?s)($methodNameToReturn.*\})(.*?$followingMethodName)").Groups[1].Value

Probably can clean up the regex a little as well but these captures do what you want.可能也可以稍微清理一下正则表达式,但这些捕获可以满足您的需求。

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

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