---
title: "Using Regex to return the first N words in a string"
url: "https://osherove.com/blog/2005/1/7/using-regex-to-return-the-first-n-words-in-a-string.md"
canonical: "https://osherove.com/blog/2005/1/7/using-regex-to-return-the-first-n-words-in-a-string.html"
published: "2005-01-07T02:47:00"
updated: "2005-01-07T02:47:00"
tags: [".Net Original", "Regex", "Tips & Tricks"]
author: "Roy Osherove"
description: "Jeff Perrin needed a function to return the first N words in a string (to create a small summary or a snippet thingy). He did it using the manual and awkward method of parsing the string manually. That method is more…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Using Regex to return the first N words in a string

By Roy Osherove January 7, 2005 In [.Net Original](https://osherove.com/blog/category/net-original), [Regex](https://osherove.com/blog/category/regex), [Tips & Tricks](https://osherove.com/blog/category/tips-tricks)

**Historical article** · Originally published January 7, 2005; technical details may be outdated.

[Jeff Perrin needed a function to return the first N words in a string](http://www2.kanga.ca/blogs/jperrin/archive/2004/12/29/225.aspx) (to create a small summary or a snippet thingy). He did it using the manual and awkward method of parsing the string manually. That method is more error prone and usually makes for less readable code. Fortunately, you can use regular expressions here quite nicely. Here's a test that makes sure that we get the first 4 words in a string and the function "FindFirstWords" that does this very easily using a simple regular expression.

What I'm doing here is that I'm using the expression to find the first 4 occurrences of text that is composed of alphanumeric text with one or more spaces after it. Then I simply iterate over the match I found. The match should contain 4 captures inside it - one for each "word" that was found.

It's not fully tested as you can see. I only wrote one test to see it works on this sort of sentence. More tests could and should be added to test other cases. In fact, if this were reall TDD, I would have started with a test of an empty string, and continued on to test getting only one word, and then two and so on.

\[Test\]

public void TestRegexFindFirstNWords()

{

      const string INPUT =

"this is word four five six seven eight nine ten eleven twelve thirteen!";

      const int NUM\_WORDS\_TO\_RETURN = 4;

      string output = **FindFirstWords** (INPUT, NUM\_WORDS\_TO\_RETURN);

      string expectedOutput = "this is word four ";

      Assert.AreEqual(expectedOutput,output);

}

private string **FindFirstWords** (string input, int howManyToFind)

{

     // thanks to [Jeff Attwood](http://www.codinghorror.com/blog/) for making this code even simpler!

      string REGEX = @"(\[\\w\]+\\s+){" + howManyToFind + "}";

      return Regex.Match(input,REGEX).Value;

}

## More in .Net Original

[All posts in .Net Original](https://osherove.com/blog/category/net-original)

- Jan 8, 2005

    ### [Making ClickOnce publishing work in VS.Net 2005 Beta 1+](https://osherove.com/blog/2005/1/8/making-clickonce-publishing-work-in-vsnet-2005-beta-1.html)

- Jan 7, 2005

    ### [Full source for The Regulator released](https://osherove.com/blog/2005/1/7/full-source-for-the-regulator-released.html)

- Jan 6, 2005

    ### [Return of the Extensibility Application Block](https://osherove.com/blog/2005/1/6/return-of-the-extensibility-application-block.html)

- Jan 5, 2005

    ### [A simple question about overloading](https://osherove.com/blog/2005/1/5/a-simple-question-about-overloading.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
