Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - Regex match for beginning of multiple words in string

In Javascript i want to be able to match strings that begin with a certain phrase. However, I want it to be able to match the start of any word in the phrase, not just the beginning of the phrase.

For example:

Phrase: "This is the best"

Need to Match: "th"

Result: Matches Th and th

EDIT: works great however it proposes another issue:

It will also match characters after foreign ones. For example if my string is "M?nn", and i search for "n", it will match the n after M?...Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
"This is the best moth".match(/th/gi);

or with a variable for your string

var string = "This is the best moth";
alert(string.match(/th/gi));

in a regex is a word boundary so th will only match a th that at the beginning of a word.

gi is for a global match (look for all occurrences) and case insensitive

(I threw moth in there to as a reminder to check that it is not matched)

jsFiddle example


Edit:

So, the above only returns the part that you match (th). If you want to return the entire words, you have to match the entire word.

This is where things get tricky fast. First with no HTML entity letter:

string.match(/th[^]*?/gi);

Example

To match the entire word go from the word boundary grab the th followed by non word boundaries [^] until you get to another word boundary . The * means you want to look for 0 or more of the previous (non word boundaries) the ? mark means that this is a lazy match. In other words it doesn't expand to as big as would be possible, but stops at the first opportunity.

If you have HTML entity characters like ä (ä) things get complicated really fast, and you have to use whitespace or whitespace and a set of defined characters that may be at word boundaries.

string.match(/sth[^s]*|^th[^s]*/gi);

Example with HTML entities.

Since we're not using word boundaries, we have to take care of the beginning of the string separately (|^).

The above will capture the white space at the beginning of words. Using will not capture white space, since has no width.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...