---
title: "How to match string between two characters using regex."  
description: "How to match string between two characters using regex."  
author: "Revati S Misra"  
published: 2023-08-29  
updated: 2023-09-04  
canonical: https://www.mindstick.com/forum/159717/how-to-match-string-between-two-characters-using-regex  
category: "c#"  
tags: ["regex", "string", "regular expression"]  
reading_time: 2 minutes  

---

# How to match string between two characters using regex.

How to [match](https://www.mindstick.com/forum/159713/regex-match-attribute-in-an-html-code) [string between two](https://www.mindstick.com/forum/159718/how-to-match-a-string-between-two-characters-if-they-exist) [characters](https://answers.mindstick.com/qa/42112/who-is-the-originator-of-avengers-characters) using regex.

## Replies

### Reply by Aryan Kumar

Sure, I can help you with that.

To match a [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) between two characters using regex, you can use the `\b` metacharacter. The `\b` metacharacter matches a word boundary. So, if you want to match the string "world" between the characters "w" and "d", you would use the following regex pattern:

```plaintext
\bwor\bd
```

The `\w` metacharacter matches any word character, which includes letters, numbers, and the underscore character.

Here is an example of how to use this regex pattern in PHP:

PHP

```plaintext
$string = "hello world";
$pattern = "\bwor\bd";

$result = preg_match($pattern, $string);

if ($result) {
 echo "The pattern 'world' was found in the string 'hello world'";
} else {
 echo "The pattern 'world' was not found in the string 'hello world'";
}
```

This code will output the following:

```plaintext
The pattern 'world' was found in the string 'hello world'
```

You can also use the `preg_match_all()` function to get all of the matches of the pattern in the string. The syntax for the `preg_match_all()` function is as follows:

PHP

```plaintext
preg_match_all(pattern, string, matches)
```

Where:

- `pattern` is the regular expression pattern that you want to match.
- `string` is the string that you want to search.
- `matches` is an array that will contain the results of the match.

The `preg_match_all()` function will return an array of all of the matches of the pattern in the string.

Here is an example of how to use this function:

PHP

```plaintext
$string = "hello world";
$pattern = "\bwor\bd";

$results = preg_match_all($pattern, $string);

foreach ($results as $match) {
 echo $match[0];
}
```

This code will output the following:

```plaintext
world
```

The `match[0]` element of the results array contains the text that was matched by the pattern.


---

Original Source: https://www.mindstick.com/forum/159717/how-to-match-string-between-two-characters-using-regex

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
