I'm using python re.
I have 2 type of strings like;
"100k bla bla bla"
"100k hours bla bla"
I want "100k" part of the string if "hours" is not next to it. (number may change, like 200 or smt. regex should match any number before k)
Expected result for "100k bla bla bla" => "100k"
Expected result for "100k hours bla bla" => ""
If you want to match any instance of a number followed by 'k' (for kilo) in a string, but only if the word "hours" doesn't immediately follow, you can use a negative lookahead in regex. Here's an example:
(\d+k)(?! hours)
This regex breaks down as follows:
(\d+k)
matches one or more digit(s) followed by the character 'k'.(?! hours)
is a negative lookahead that asserts the string ' hours' does not immediately follow the current position.You can use this regex in Python as follows:
import re
str1 = "100k bla bla bla"
str2 = "100k hours bla bla"
pattern = r"(\d+k)(?! hours)"
match1 = re.search(pattern, str1)
if match1:
print(match1.group())
match2 = re.search(pattern, str2)
if match2:
print(match2.group())
else:
print("No match")
The above python script will print 100k
for the first string and No match
for the second string. If you want to consider all whitespaces or even no whitespace between 'k' and 'hours', you can use \s*
which matches zero or more whitespace characters.
(\d+k)(?!\s*hours)