简体   繁体   English

以特定字符串开头的单词的正则表达式(javascript)

[英]regular expression for words beginning with a certain string (javascript)

I am trying to write a regular expression in javascript for finding if any words in a sentence start with a particular phrase. 我试图用javascript写一个正则表达式,以查找句子中是否有以特定短语开头的单词。 Eg, I'd like to know if "by" is contained at the beginning of any word in the following sentence : "The Tipping Point by Malcolm Gladwell". 例如,我想知道“ by”是否包含在以下句子的任何单词的开头:“ Malcolm Gladwell的引爆点”。

I tried using \\b but /\\bsor/ will match a sentence like 'Mary's organ is broken.' 我尝试使用\\b/\\bsor/将匹配“玛丽的器官坏了”这样的句子。 ie it treats punctuation as a word boundary and starts matching after them. 即,它将标点符号视为单词边界,并在它们之后开始匹配。 Any thoughts? 有什么想法吗?

/(?:\\s|^)bar/ -- perhaps -- although see the answer for splitting it first /(?:\\ s | ^)bar / -也许-尽管请先参阅拆分的答案

/(?:\s|^)bar/.test("bar")     // true
/(?:\s|^)bar/.test("foo bar") // true
/(?:\s|^)bar/.test("foo'bar") // false
/(?:\s|^)bar/.test("Sentence One.bar Two.") // false ... "oops"?

How about using split on the sentence to try your expression on every word? 在句子上使用split试一下每个单词的表达怎么样?

You could also use indexOf rather than a regexp. 您也可以使用indexOf而不是regexp。

On Regexpedia, there is an article has the code and explainations. 在Regexpedia上,有一篇文章提供了代码和说明。

JavaScript Search for Lines Beginning with a Word JavaScript搜索以单词开头的行

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

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