Python regular expression. Find a sentence in a sentence
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p>

<p>I tried with regular expression, but it doesn't work :(</p>

<pre><code>import re


value = "Chris and 34K others"

m = re.search("(.K.others.)", value)

if m:
    print "it is true"
else:
    print "it is not"
</code></pre>

<p>If you want to match something <em>within</em> the string, use <code>re.search</code>. <code>re.match</code> starts at the beginning, Also, change your RegEx to: <code>(K.others)</code>, the last <code>.</code> ruins the RegEx as there is nothing after, and the first <code>.</code> matches any character before. I removed those:</p>

<pre><code>&gt;&gt;&gt; bool(re.search("(K.others)", "Chris and 34K others"))
True
</code></pre>

<p>The RegEx <code>(K.others)</code> matches:</p>

<pre><code>Chris and 34K others
            ^^^^^^^^
</code></pre>

<p>Opposed to <code>(.K.others.)</code>, which matches nothing. You can use <code>(.K.others)</code> as well, which matches the character before:</p>

<pre><code>Chris and 34K others
           ^^^^^^^^^      
</code></pre>

<p>Also, you can use <code>\s</code> to escape space and match only whitespace characters: <code>(K\sothers)</code>. This will literally match K, a whitespace character, and others.</p>

<p>Now, if you want to match all preceding and all following, try: <code>(.+)?(K\sothers)(\s.+)?</code>. Here's a link to <a href="https://repl.it/D2mD/1" rel="nofollow">repl.it</a>. You can get the number with <a href="https://repl.it/D2mD/2" rel="nofollow">this</a>.</p>

python regex python-2.7