简体   繁体   English

正则表达式匹配句子javascript中的第一个和最后一个单词?

[英]Regex for match first and last words in a sentence javascript?

I am having some problem coming up with the pattern matching. 我在模式匹配方面遇到了一些问题。 I have a sentence which has "Pyramids are mindblowingly awesome" I would like to write a regex which matches with pyramids and awesome ie, first and last words of the sentence should match with pyramids and awesome . 我的句子中有"Pyramids are mindblowingly awesome"我想写一个正则表达式,它与金字塔匹配并且很棒,也就是说,句子的首尾都应该与pyramids匹配并且awesome And I am considering case-insensitive. 我正在考虑不区分大小写。 I tried this /pyramids(...)/awesome/i Could anyone help me with this. 我试过了/pyramids(...)/awesome/i有人可以帮我/pyramids(...)/awesome/i

Edit: I am looking for exact words in the sentence. 编辑:我正在寻找句子中的确切单词。

Thank you. 谢谢。

You can use RegExp /^\\w+|\\w+$/g to match word at beginning of string or word at end of string. 您可以使用RegExp /^\\w+|\\w+$/g匹配字符串开头的单词或字符串结尾的单词。

 let str = "Pyramids are mindblowingly awesome"; let matches = str.match(/^\\w+|\\w+$/g); console.log(matches); 

/^pyramids.*awesome$/i

将确保字符串以金字塔开头和以超赞结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM