搜索包含回车符和换行符的子字符串

时间:2017-03-23 09:48:54

标签: python regex python-2.7

我有一个Python脚本,它使用套接字连接与另一个应用程序(确切地说是连接到嵌入式目标的调试器)进行通信。

调试器的响应长度可能不同,可以跨越多行,但它们始终以public partial class Form1 : Form { public Form1() { InitializeComponent(); } public Form1(string cell1, string cell2, string cell3, string cell4) { InitializeComponent(); //Save data to our list using global class that Global.SetRow = new Global.GridRows() { Cell_1 = cell1, Cell_2 = cell2, Cell_3 = cell3, Cell_4 = cell4 }; } } 或{{1}}结尾。我想捕获{{1}}或{{1}},包括换行符。

使用(例如{{1}}表示True)的正则表达式似乎在regex101.com上进行测试时有效,但在使用Python运行时仅返回{{1}}。

带有示例响应字符串的示例代码:

{{1}}

我知道我正在使用的正则表达式存在根本性的错误。我也尝试过如下所示的正面观察,这似乎有效,但我不确定这是否是正确方式:

{{1}}

1 个答案:

答案 0 :(得分:1)

您说您需要匹配True\r\nFalse\r\n,然后您的模式中的^[.]+|[\r]+|是多余的。使用

re.search(r'[\r\n]*\b(?:True|False)[\r\n]*$', s)

如果您在[\r\n]*True之前不需要换行符,请忽略最初的False

<强>详情:

  • [\r\n]* - 零个或多个CR或LF符号
  • \b - 字边界
  • (?:True|False) - TrueFalse整个单词
  • [\r\n]* - 如上所述
  • $ - 字符串结束。