简体   繁体   中英

How to search a multiple-word-string (exact match) in a string?

I've found similar questions to this one, but they are not quite what I was looking for, since they are asking about specific and singular words not multiple. I have a string k (which is a key in a dictionary) that is generated automatically by a function (depending on user input) and it looks like this: " condition1 ^ condition2 ^ condition3 ^ ..." (at least one condition).

Each condition can looks like this:

  1. a > b
  2. a <= c
  3. b < a <= c

Now, what I'm trying to do is to search in ka certain piece of string, let's say "a <= c" for a conditional: if "a <= c" in k then ... . The problem is that there could be "aa", "ba", "aaa", "ca" etc. instead of "a", in which case I don't want the conditional to be True. How do I deal with this? I've been reading the re module documentation but I'm confused

UPDATE I initially used re.findall as suggested by alec_djinn, adapting it to my needs:

'(?<![^\s])a <= c(?![^\s])'

But I had some problems with it. So I decided not to use regex and I instead checked if "a<=c" was equal to any

g for g in [k.split()[g]+k.split()[g+1]+k.split()[g+2] for g in xrange(len(k.split())-2)]. 

It works. Any comments on this solution?

\ba <= c\b

你可以做一个re.search这一点。

You can use (?<![az]) that means "if it is not preceded by any lowercase letter".

Here an example.

import re

str_a = 'b a <= c'
str_b = 'ba <= c'

m = re.findall('(?<![a-z])a <= c', str_a)
n = re.findall('(?<![a-z])a <= c', str_b)
print m, n

It prints:

['a <= c'] []

It finds a match for str_a only and not for str_b.

I would probably have used vks's solution, which seems the simplest. However, if you want to avoid regexs and you know your string is separated by single spaces everywhere, you could also do it like this:

(' ' + condition + ' ') in (' ' + k + ' ')

Your solution involving splitting the string and recombining it will work, but only for 3 element strings and it will take more time and memory than necessary.

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