Skip to content Skip to sidebar Skip to footer

Regular Expression Stop After First Match

So I have the following pattern work sleep work eat I need a regular expression that finds only the first word work and not all of them, I've never understood regular expressions.

Solution 1:

I've never understood regular expressions.

So why you want to use them? If you do not understand them, use a different approach using string/array operations. You should never use code you don't understand - cause if in doubt you would not be able to fix it!

String example: Use your programing languages indexOf() method to find the start position of "work".

Array example: Split the string at the occurence of searchtag - and check if you have more than one result.

If you just need to figure out IF the string appears, use .contains() etc...


Solution 2:

You are matching it globally. I don't know for what purpose nor where you need it. Check it here http://regexpal.com/ Make sure you have unchecked the global check button.

If you match it globally it searches the whole document/text and match it everywhere it can. This is why you get work matched twice

Solution 3:

Here it is in javascript

text.match(/(work)/);

Post a Comment for "Regular Expression Stop After First Match"