简体   繁体   中英

Searching for a string within a strict format

I want to search for a sub-string using the python re library with the following format:

(some word)(\)term1(\)(some word) (some word)(\)term2(\)(some word)

The groups in brackets are optional, term1 and term2 must be in the string within that format.

A few examples of what it should detect:

  • random sentence word\term1 term2 end of random sentence
  • random sentence term1 term2 end of random sentence
  • random sentence word\term1\word word\term2\word end of random sentence

so far i have tried this:

r'((\W+|^)term1((\W))*)(\w+|) (\w+|)(\W|)term2(\W|)'

but it does not work

My guess is that, maybe

^(\([^)]*\))?(\(\\\))?term 1(\(\\\))?(\([^)]*\))?\s(\([^)]*\))?(\(\\\))?term 2(\(\\\))?(\([^)]*\))?$

might work.

Demo

This pattern should work:

^[\w ]*\\?term1\\?[\w ]*\\?term2\\?[\w ]*$

Python demo:

import re

pattern = re.compile(r"^[\w ]*\\?term1\\?[\w ]*\\?term2\\?[\w ]*$")

string1 = r"random sentence word\term1 term2"
string2 = r"random sentence term1 term2 end of random sentence"
string3 = r"random sentence word\term1\word word\term2\word end of random sentence"

print(bool(re.search(pattern, string1)))
print(bool(re.search(pattern, string2)))
print(bool(re.search(pattern, string3)))

Output:

 True True True

Use the following:

^.*\s(?:\w+\\)?term1(?:\\\w+)?\s(?:\w+\\)?term2(?:\\\w+)?\s.*$

Demo & explanation

import re

lines = [
    r'random sentence word\term1 term2 end of random sentence',
    r'random sentence term1 term2 end of random sentence',
    r'random sentence word\term1\word word\term2\word end of random sentence'
]

regex = re.compile(r'(\b\w+\b)?\\?term1\\?(\b\w+\b)? (\b\w+\b)?\\?term2\\?(\b\w+\b)?')
for line in lines:
    m = regex.search(line)
    if m:
        print('Match:', m.group(0))
    else:
        print("No match")

Prints:

Match: word\term1 term2
Match: term1 term2
Match: word\term1\word word\term2\word

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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