0

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

alvas
123k118 gold badges504 silver badges810 bronze badges
asked Jan 8, 2016 at 17:40
1
  • changed the tags so that it's a little more relevant, it has nothing much to do with nlp or nltk. Commented Jan 8, 2016 at 19:31

3 Answers 3

2

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.

answered Jan 8, 2016 at 17:54
Sign up to request clarification or add additional context in comments.

Comments

0

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>
answered Jan 8, 2016 at 18:09

Comments

0

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
answered Jan 8, 2016 at 20:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.