0

I've a list ['test_x', 'text', 'x']. Is there any way to use regex in python to find if the string inside the list contains either '_x' or 'x'?

'x' should be a single string and not be part of a word without _.

The output should result in ['test_x', 'x'].

Thanks.

3
  • Is using regex a necessity? You can do the same thing with a one-line list comprehension Commented May 14, 2020 at 2:13
  • Regex is not necessary. Commented May 14, 2020 at 2:13
  • It looks like you are looking to filter a list. A regex may or may not be required. Commented May 14, 2020 at 2:15

3 Answers 3

2

Using one line comprehension:

l = ['test_x', 'text', 'x']

result = [i for i in l if '_x' in i or 'x' == i]
Sign up to request clarification or add additional context in comments.

3 Comments

TypeError: 'in <string>' requires string as left operand, not list
Op says the word contains _x or x
'x' == i is needed since I don't want words which has x in between. Only _x or if str itself is x. Answer works though. Thanks.
0

You can use regexp this way:

import re
print(list(filter(lambda x: re.findall(r'_x|^x$',x),l)))

The regexp searches for exact patterns ('_x' or 'x') within each element of the list. applies the func to each element of the iterable.

You can make your expression more genric this way:

print(list(filter(lambda x: re.findall(r'[^A-Za-z]x|^\W*x\W*$',x),l)))

Here am telling python to search for expressions which DON't start with A to Z or a to z but end in x OR search for expressions that start and end with 0 or more non-word characters but have x in between. You can refer this quick cheatsheet on regular expressions https://www.debuggex.com/cheatsheet/regex/python

Comments

0
[re.findall('x|_x', s) for s in your_list]

1 Comment

Please put your answer always in context instead of just pasting code. See here for more details.

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.