+ 9
How can regex find the middle three letters of a 5char-word?
Example findall(regex,"12345")=234 General case: find string w.o first and last.
15 ответов
+ 9
Oma Falk Based on the question:
"How can regex find the middle 3 letters of a 5 char-word?"
I'm assuming the word can include any non-whitespace alphanumeric character like this one: "12345"
The regexes in this thread would work with this example.
However, many may also incorrectly work for the following invalid values:
" 234 "
" 2345"
"1234 "
"1 3 5"
"123 5"
The same regexes may not properly extract "234" from 5 char values with leading and/or trailing whitespaces like the following:
" 12345"
"12345 "
" 12345 "
I believe the proper regex to cover all positive and negative test cases would be:
re.search(r'(?<!\S)\S(\S{3})\S(?!\S)', s)
- The \S matches on non whitespace characters.
- (?<!\S) is a negative look behind.
- (?!\S) is a negative look ahead.
To match on all but the first and last characters, replace (\S{3}) with (\S+)
The code below runs tests on the RegEx patterns posted in this thread for review with mine posted last:
https://code.sololearn.com/cnnrMYDDmP2x/
I hope this helps.
+ 7
import re
print(re.findall(r".(.{3}).", "12345"))
print(re.findall(r".(.{3}).", "hello"))
print(re.findall(r".(.{3}).", "12AA5"))
same "pattern" used for all three.
+ 5
reg = re.compile(r'^(\d|\w)(\d{3}|\w{3})(\d|\w)#x27;)
mo = reg.search('12345')
print(mo.group(2))
It works for letters or numbers. Not both
+ 4
Code Crasher want to learn regex.
It is very mighty.
After 3 hours I could find a regex for a String if it is a tictactoe winner.
Hope to become a bit quicker.
+ 4
Ahhh groups...good.
+ 4
Code Crasher
Yes...wehre else👍👍
+ 3
reg = r"\B.+\B"
"The \B metacharacter is used to find a match, but where it is NOT at the beginning/end of a word." w3Schools.com
+ 3
Regex is such a lovely topic.
You could use a lookaround pattern (lookbehind and lookahead), like:
import re
m=re.match(r"(?<=.).{3}(?=.)", your_5_chr_str).group()
(since + and other special characters are greedy, you don't have to specify {3} though.)
You could also capture it in a group:
m=re.match(r".(.+).",your_5_chr_str).group(1)
+ 2
This is what helped me get to grips with regular expression after the tutorial in Sololearn:-
https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/python_regex.asp
+ 2
David Carroll yeeeees got it for 90%
+ 1
Code Crasher brilliant
+ 1
Folks... I need a regex for my feed post with state machine.