仅在字符串末尾匹配整个句子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅在字符串末尾匹配整个句子相关的知识,希望对你有一定的参考价值。

比方说,我们要检查speech是否包含特定句子reference但在它的最后和结尾

这里是reference

let reference = "have you ever look at someone";

基于此reference,我们想比较speech并返回匹配项或不匹配项:

let speech = "blaaaah have you ever look at someone"; // Match because 'have you ever look at someone' is at the end of speech
let speech = "have you ever look at someone blaaaah"; // No match because something else came after 'have you ever look at someone'

问题是我无法区分上述语音示例,并且代码始终返回Match:

//let speech = "blaaaah have you ever look at someone"; // matched
let speech = "have you ever look at someone blaaaah"; // No match 

let reference = "have you ever look at someone";

if(new RegExp("\\b"+reference+"\\b").test(speech))
  console.log("Finally Matched!")
 else 
  console.log("No Match At Last!")
答案

这是您要寻找的吗?

//let speech = "blaaaah have you ever look at someone"; // matched
let speech = "have you ever look at someone blaaaah"; // No match 

let reference = "have you ever look at someone";

if(new RegExp("\\b"+reference+"\\b$").test(speech))
  console.log("Finally Matched!")
 else 
  console.log("No Match At Last!")
另一答案

您可以使用endsWith进行如下验证,

var str = "Hello world, welcome to the universe.";
var n = str.endsWith("universe.");

根据您的情况

  //let speech = "blaaaah have you ever look at someone"; // matched
let speech = "have you ever look at someone blaaaah"; // No match 

let reference = "have you ever look at someone";

if(speech.endsWith(reference))
  console.log("Finally Matched!")
 else 
  console.log("No Match At Last!")

以上是关于仅在字符串末尾匹配整个句子的主要内容,如果未能解决你的问题,请参考以下文章

如何颠倒整个句子的大小写?

如果字符串与列表中的字符串匹配,我如何从句子中删除字符串

在javascript中包含整个字符串中的单词[关闭]

正则表达式匹配整个句子。

多模式串字符串匹配模板题

18.10.29 多模式串字符串匹配模板题~AC自动机