Python regex pattern: find single “o” letters (multiple o-s should be excluded) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python regex pattern: find single “o” letters (multiple o-s should be excluded)

['xxoxoxoxoxoxooxxxxox\n', 'xxxxxxxxxxxxxxxxooox\n', 'xoxoxoxoxoxoxoxoxoxo\n', 'ooxoxoxoxoxoxoxooxox\n', 'xxxxxxxxxxxxxxxxoooo\n', 'xxxxxxxxxxxxxxxxxxxx\n', 'oooooooooooooooooooo\n', 'xxxxxxxxxxooxxxxxxxx\n', 'xooxxxxxxxxxoxxxxxoo\n', 'xxxxxxoxxxxxxxoxxooo\n', 'xooooooooxoooooooxxx\n', 'ooooooxoxoxoxoxoxoxo\n', 'oxxxxxxxxxxxxxxxxxoo\n', 'xxxxxxxxxxxxooooooox\n', 'oxxxxxxxxxxxxxoooooo\n'] Imagine that this string is a theater where you have to find all free single seats. x = seats sold out o = seats free With “free single seat” I mean seats that (1) has no free neighbors (no multiple “o”-s) and (2) not located at the beginning or end of a row (as eg. in the last line). I tried the following RegEx pattern: [^o]o[^o] Does not work because it can’t find all single “o”, eg. in “xoxoxox” it misses the second “o”. Any idea for solution?

2nd Mar 2020, 10:24 PM
Prof. Dr. Zoltán Vass
5 Answers
+ 2
okay... (?<=x)o(?=x) maybe.. its using lookahead and lookbehind to make sure it has x around it it works in js, it should works too in python const x = [...'xoxoxoxox'.matchAll(/(?<=x)o(?=x)/g)] i tested it again with oxoxoox its only return 1 o.
2nd Mar 2020, 10:56 PM
Taste
Taste - avatar
+ 1
Taste Thanks! Your code helped me, I didn’t know these lookahead and lookbehind tricks. Actually, I had to extend it because line start and end was not recognized. This works perfectly: ((?<=\')|(?<=x))(o)((?=x)|(?=\\))
2nd Mar 2020, 11:09 PM
Prof. Dr. Zoltán Vass
+ 1
good to know
2nd Mar 2020, 11:10 PM
Taste
Taste - avatar
0
why not just o+ ? or just o if you only need to find every single o seperately
2nd Mar 2020, 10:32 PM
Taste
Taste - avatar
0
Taste I have added more details to my question, eg. multiple “o”-s are not allowed.
2nd Mar 2020, 10:48 PM
Prof. Dr. Zoltán Vass