单词的模式存在于字符串中



我想知道字符串中是否存在某种单词模式。例如,在下面的字符串中,我想知道单词"wish"one_answers"allow"是否出现。在这里,排序很重要,所以我只想在"允许"之前出现"愿望"时返回True。"我希望平台能够允许用户更改设置"结果:正确一个反例:"我允许我的设置更改,只希望这能逆转"结果:错误

如有任何帮助,将不胜感激

我去了Regex101.com,创建了一个满足您需求的Regex表达式:

/wish(.?|.*)allow/

这意味着"在文本中的任何位置找到单词‘wish’,后跟零、一或许多其他字符,后跟单词‘allow’"。

Regex101.com是一个构建Regex表达式的好沙盒。每当我不确定Regex模式匹配应该如何格式化时,我都会使用这个工具。

您可以尝试使用我在javascript中实现的概念。

你得到的结果总是在南瓜之前出现的苹果。

<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>

您实际上并不需要正则表达式:

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

最新更新