查找字符串中的特定单词+任意单词+特定单词python

时间:2019-11-19 16:04:29

标签: python regex string find

我想在一个字符串中找到一个单词组合,其中某些/大多数单词是特定的,但一个可以是任何东西(任何单词,字符)。

sentence = 'There are five cats and seven dogs at the park.'

find_in_string = 'cats and ... dogs'

if find_in_string in sentence:
   print(find_in_string)

我知道可以在此时实施正则表达式,但是确切的内容和方式有点令人困惑,所以谢谢!!

4 个答案:

答案 0 :(得分:1)

您正在寻找.运算符,它是任何字符的通配符。例如,在您的示例中,您可以编写表达式

r'cats and .+ dogs`

这就是说“先查找字符串cats and(注意空格),然后查找所有字符,直到出现另一个空格后紧跟dogs”。如果要限制anddogs之间匹配的字符,可以使用[a-z]之类的字符而不是.来限制小写字母的匹配。 / p>

答案 1 :(得分:1)

您是对的。您可以为此使用

def record_club_minutes(user_id, club_id, purchase, fund):
    user = User.query.get_or_404(user_id)
    club = Club.query.get_or_404(club_id)
    members = club.members
    form = create_club_minutes_form(club, purchase, fund)
    if form.validate_on_submit():
            **extra things omitted**
            minute = Minutes(club_id=club_id, date=form.date.data, ..., minute=form.notes.data)
            db.session.add(minute)
            #WHERE IT GETS MESSY AKA I DON'T KNOW HOW TO GET THE DATA CORRECTLY, ENUMERATE DOES NOT WORK FOR QUERYSELECTMULTIPLEFIELD
            for index, field in enumerate(form.attendance):
                    attendance = Attendance(student_name=members[index].firstname + ' ' + members[index].lastname, present= field.data, minutes_id=minute.id)
                    minute.attendance.append(attendance)
            db.session.commit()
            flash('Minutes successfully recorded', 'success')
            return redirect(url_for('clubs.view_club_name', user_id=user.id))
    return render_template('record_minutes.html', title='Record', form=form, user=user, club=club, members=members)

答案 2 :(得分:1)

使用re.search并将.*用作通配符:

sentence = 'There are five cats and seven dogs at the park.'
find = re.search(r'cats and .*dogs', sentence)
if find:
    print(find[0])

打印:

'cats and seven dogs'

答案 3 :(得分:0)

谢谢!

sentence ='There are five cats and seven dogs at the park.'
find_in = re.search(r'cats and \S+ dogs', sentence)
if find_in:
    print(find_in)