Reputation: 1605
I have a regex expression but its not working for all cases.
I need it to be able to match any case of the following within two levels of depth:
If this word "test_word" is in the statement return true
What I been using hasn't been working
('^/[^/]*/test_word/.+')
or
('^/test_word/.+')**
So I'm matching in statements with dirs such as:
/user/test_word
/test_word
/test_word/test_word/
but false in this example because its beyond two levels. I don't want positive for anything beyond two levels
/something/something/test_word/
and anything you can think of that could happen.
Upvotes: 0
Views: 296
Reputation:
For 2 levels
^/(?:[^/\r\n]*/){0,1}test_word(?:/|$)
Expanded:
^
/
(?: [^/\r\n]* / ){0,1}
test_word
(?: / | $ )
For N levels (>= 2)
^/(?:[^/\r\n]*/){0,N-1}test_word(?:/|$)
Expanded:
^
/
(?: [^/\r\n]* / ){0,N-1}
test_word
(?: / | $ )
Upvotes: 0
Reputation: 6333
i would recommend you not to use regex in such case. what you want here is partial perfect match instead of pattern match, so it's a waste of computation resource. you could do it by simply:
import os
filepath = #init
hier = filepath.split(os.path.sep)
print 'right' if hier[1] == 'test_word' or hier[2] == 'test_word' else 'wrong'
Upvotes: 1
Reputation: 177685
How about:
lines = '''\
/user/test_word
/test_word
/test_word/test_word/
/something/something/test_word/
/user/test_word/
/test_word/
/test_word/test_word
/something/something/test_word
/user/test_word/more
/test_word/more
/test_word/test_word/more
/something/something/test_word/more
/something/test_word/test_word
/test_wordxx
/something/test_wordxx
'''.splitlines()
import re
for line in lines:
if re.match('/(?:[^/]+/)?test_word(?:/|$)',line):
print('YES',line)
else:
print('NO ',line)
Output:
YES /user/test_word
YES /test_word
YES /test_word/test_word/
NO /something/something/test_word/
YES /user/test_word/
YES /test_word/
YES /test_word/test_word
NO /something/something/test_word
YES /user/test_word/more
YES /test_word/more
YES /test_word/test_word/more
NO /something/something/test_word/more
YES /something/test_word/test_word
NO /test_wordxx
NO /something/test_wordxx
Not sure if you want the 3rd to last one.
Upvotes: 1
Reputation: 335
Assuming this is python 2.7 (haven't worked with 3) you don't really need any libraries just the builtin string functions this is how I approached it:
testword = "test_word"
stringToCheck = "/something/something/TeSt_wOrD/"
def testForWord(string):
if testword in string.lower(): return True
else: return False
print testForWord(stringToCheck)
As you can see it checks for any case because it just checks when all cases are lower case. I'm not 100% sure if thats what you need but I think that should do it :D.
Upvotes: 1
Reputation: 174706
I think you want something like this,
^(?=.*?/test_word)(?!.*?//)\/(?:[^/]*)(?:/[^/]*)?/?$
Upvotes: 2