Pigna
Pigna

Reputation: 2924

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 k a 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?

Upvotes: 1

Views: 715

Answers (3)

Rodrigo Queiro
Rodrigo Queiro

Reputation: 1336

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.

Upvotes: 1

alec_djinn
alec_djinn

Reputation: 10789

You can use (?<![a-z]) 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.

Upvotes: 2

vks
vks

Reputation: 67968

\ba <= c\b

You can do a re.search for this.

Upvotes: 2

Related Questions