0

I'm working with regex in python and I'd like to search for all the words in a string except one word. Code:

import re
string = "The world is too big"
print re.findall("regex", string)

If I want to get all the words except for the word "too" (so the output will be ["The", "world", "is", "big"]), How can I implement this in regex?

4
  • 3
    Not every string problem is a regex problem. Split on whitespace, then filter your list to remove the items you don't want. Commented Mar 24, 2017 at 18:31
  • If you want to play around while learning regular expressions, the online testers are pretty convenient: regex101.com is one. Commented Mar 24, 2017 at 18:35
  • ' '.join(list(filter(lambda w: w != 'too', string.split()))) or ' '.join(w for w in string.split() if w != 'too') Commented Mar 24, 2017 at 18:39
  • matches all strings except too: ^(?!too$).* Commented Mar 24, 2017 at 18:58

2 Answers 2

1

You don't even need to use regex for this task, simply use split and filter:

sentence = "The world is too big"
sentence = list(filter(lambda x: x != 'too', sentence.split()))
print(sentence)
Sign up to request clarification or add additional context in comments.

5 Comments

I'm not crazy about the use of string for a variable name here, especially when it becomes a list. Please consider renaming your variables.
sure, I only used it because of OP's example
In Python 3, filter returns a generator, so you'd have to do print(list(sentence)), or something like that to actually see the words.
@not_a_robot I'm pretty sure the OP's using python 2, but adding a list() wouldn't hurt
@abccd I just added my comment for future folks coming to this question who may be using 3 :)
1

Delete 'too' in string, then split string.

re.sub(r'\btoo\b','',string).split()
Out[15]: ['The', 'world', 'is', 'big']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.