Reputation: 1111
I want to find if a certain pattern of words exists in a string. As an example, in the string below, I want to know if the words "wish" and "allow" occur. Here, ordering matters so I want to only return True if "wish" appears before "allow". "I wish the platform gave the ability to allow one to change settings" Result: True a counter-example: "I allowed my setting to change, only wish this could be reversed" Result: False
Any help will be appreciated
Upvotes: 0
Views: 32
Reputation: 7840
You don't actually need regex for this:
def checkwordorder(phrase, word1, word2):
try:
return phrase.lower().index(word1.lower()) < phrase.lower().index(word2.lower())
except ValueError:
return False
>>> checkwordorder('I wish the platform gave the ability to allow one to change settings', 'wish', 'allow')
True
>>> checkwordorder('I allowed my setting to change, only wish this could be reversed', 'wish', 'allow')
False
Upvotes: 0
Reputation: 163
You can try using my concept implemented in javascript.
you always get the result apple which is appeared just before pumpkin.
<html>
<body>
<p>Click the button to display the last position of the element "Apple" before pumpkin</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var fruits = ["Banana","Orange","Apple","Mango","Banana","Orange","Apple","Mango","pumpkin","Apple"];
var a = fruits.indexOf("pumpkin");
var b = fruits.lastIndexOf("Apple",a);
var x = document.getElementById("demo");
x.innerHTML = b;
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 686
I went to Regex101.com and created a Regex expression that meets your needs:
/wish(.?|.*)allow/
This means "find the word 'wish' anywhere in the text, followed by zero, one, or many other characters, followed by the word 'allow'".
Regex101.com is a great sandbox for building Regex expressions. Any time I'm not sure how the Regex pattern-matching should be formatted, I use this tool.
Upvotes: 2