复杂的Preg_Match -在找到关键字后匹配500个字符,但直到下一个换行才开始


Complicated Preg_Match - match 500 characters after finding a keyword but dont start until the next line break

首先解释一下我是php新手,我是preg_match新手,我觉得很困惑,我想做的是找到一个关键字:exception:然后从下一行开始抽出300个字符

我已经有一个pregmatch但是想提高它,我做的是把300字的关键字,但问题是异常的名称关键字之后,下一行的代码错误,除了可以在任意数量的书面语言,但代码错误后异常独立于语言所以我想过滤例外,因为它不同的语言所以我知道如果异常时100%的匹配比较。

下面是一些例外的例子:

Exception: System.Runtime.InteropServices.COMException (0x800401D0): OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Windows.Clipboa
exception: Specified cast is not valid.
Query:Select * from TourneyData where Player_id = 1412
14:14:18.868 [SetCurrentPlayer:12 - DatabaseBase.HandleDatabaseConnectionException] 4: System.InvalidCastException: Specified cast is not valid.
at NpgsqlTypes.NpgsqlTimeStamp.op_I
Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.Application.ThreadContext.ExitCommon(Boolean disposing)
at System.Windows.Forms.Application.ExitInternal()
at System.Windows.Forms.Application.Exit(C

所以我计划如何得到代码错误是显示所有信息在关键字exception之后的下一行:

在最后一个例子中,我想要的输出是:
at System.Windows.Forms.Application.ThreadContext.ExitCommon(Boolean disposing)
at System.Windows.Forms.Application.ExitInternal()
at System.Windows.Forms.Application.Exit(C

好的,下面是我用来收集关键字后300个字符的代码:

// Snippet length constant
define(SNIPPET_LENGTH, 300);
$pos = stripos($body,$keyword);   
$snippet_pre = substr($body, $pos, SNIPPET_LENGTH);

现在我还在几个函数中使用preg_match来获取信息,例如代码中有这样的查找日志信息:

12:19:42.787 [Main:1 - Bootstrapper.LogSystemInfo] Current culture: it-IT
12:19:42.865 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Name: Microsoft Windows 7 Home Premium 
12:19:42.865 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Architecture: 64 bit
12:19:42.865 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Service Pack: Service Pack 1

这是preg_match,只包括它可能有助于区分如何区分换行,因为它捕获了来自换行之前的所有信息,但我不知道如何获得换行之后的300个字符:

    preg_match('/Current culture: (.*)/', $body, $culture_pre);
preg_match('/Operating System Name: (.*)/', $body, $os_name_pre);
preg_match('/Operating System Architecture: (.*)/', $body, $os_bit_pre);
preg_match('/Operating System Service Pack: (.*)/', $body, $os_service_pack_pre);

如果您需要其他信息请告诉我

preg-match和所有regex在遇到'n'r'n时通常很难处理。

您可以使用m修饰符来解决某些情况,但它所做的唯一事情是改变保留字符$^的行为,使它们匹配字符串的结束或开始,同时考虑到'n,因为它会将字符串拆分为不同的子字符串。我认为这对你的问题不起作用,但你可以试试。

还有其他可能的方法来解决这个问题,尽管不是所有的方法都是完全干净的:

1-简单的方法:在应用regex之前删除'r'n'r:

$chars=array("'r'n", "'n", "'r");
$string=str_replace($chars, '', $string);

正则表达式是这样工作的,但是如果你想保持多行,你会失去字符串的格式。

2-简单而不那么干净的方法:将'n更改为您知道它不会出现在字符串中的特殊字符(例如#),应用正则表达式,再次将特殊字符更改为'n。如果你时间紧迫的话,它是有效的。

3-不那么容易,干净的方式:使用'n作为关键字分割字符串,应用preg_match()一行一行地读取它,如果它匹配,保存以下2或3(或任何你需要保存的数字)行。