Python正则表达式可在两个字符串之间找到字符串

时间:2019-07-10 18:41:58

标签: python regex python-3.x

我试图使用Regex来查看字符串的特定部分并取其间,但是我无法为此获得正确的Regex模式。

我最大的问题是试图为此建立正则表达式模式。我已经尝试了许多与所列示例接近的变体。应该很近。

import re

toFind = ['[]', '[x]']
text = "| Completed?|\n|------|:---------:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

# Regex to search between parameters and make result lowercase if there are any uppercase Chars
result = (re.search("(?<=Link Created)(.+?)(?=Research Done)", text).lower())

# Gets rid of whitespace in case they move the []/[x] around
result = result.replace(" ", "")

if any(x in result for x in toFind):
    print("Exists")
else:
    print("Doesn't Exist")

快乐之路: 我采用字符串(文本),并使用Regex表达式来获取Link Created和Research Done之间的子字符串。

然后将结果小写并除去空格,以防它们移动[] / [x] s。然后查看“ []”或“ [x]”的字符串(结果)并打印。

实际输出: 目前我得到的只是None,因为Regex语法已关闭...

3 个答案:

答案 0 :(得分:1)

我认为这是using (connection) { // Create a DataTable with the modified rows. DataTable addedStudents = StudentsDataTable.GetChanges(DataRowState.Added); // Define the INSERT-SELECT statement. string sqlInsert = "INSERT INTO dbo.Students (xxx, yyy)" + " SELECT s.xxx, s.yyy" + " FROM @tvpStudents AS s;" // Configure the command and parameter. SqlCommand insertCommand = new SqlCommand(sqlInsert, connection); SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@tvpStudents", addedStudents); tvpParam.SqlDbType = SqlDbType.Structured; tvpParam.TypeName = "dbo.StudentTableType"; // Execute the command. insertCommand.ExecuteNonQuery(); } 换行符引起的问题。您可以这样使用\n来解决此问题:

[\s\S]+

答案 1 :(得分:1)

如果您希望.匹配换行符,则可以使用re.S选项。

此外,在继续调用之前检查正则表达式是否匹配似乎是一个更好的主意。您对lower()的呼叫给了我一个错误,因为正则表达式不匹配,因此仅当result.group(0).lower()的评估为true时才呼叫result更安全。

import re

toFind = ['[]', '[x]']
text = "| Completed?|\n|------|:---------:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

# Regex to search between parameters and make result lowercase if there are any uppercase Chars
result = (re.search("(?<=Link Created)(.+?)(?=Research Done)", text, re.S))

if result:
    # Gets rid of whitespace in case they move the []/[x] around
    result = result.group(0).lower().replace(" ", "")

    if any(x in result for x in toFind):
        print("Exists")
    else:
        print("Doesn't Exist")
else:
    print("re did not match")

PS:所有re选项都记录在re module documentation中。在re.DOTALL中搜索re.S(它们是同义词)的详细信息。如果要组合选项,请使用按位或。例如,re.S|re.I将有.个匹配换行符,并且不区分大小写。

答案 2 :(得分:1)

除非正要丢失某些内容,否则正则表达式似乎对于该特定工作而言过于矫kill过正(除非我也不清楚,为什么您需要从子字符串中删除空格的步骤)。您可以仅在“链接已创建”上拆分,然后在“研究完成”上拆分以下字符串。

text = "| Completed?|\n|------|:---------:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

s = text.split("Link Created")[1].split("Research Done")[0].lower()

if "[]" in s or "[x]" in s:
    print("Exists")
else:
    print("Doesn't Exist")

# Exists
相关问题