Easy done:

(?<=\[)(.*?)(?=\])

Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:

  • is preceded by a [ that is not captured (lookbehind);
  • a non-greedy captured group. It's non-greedy to stop at the first ]; and
  • is followed by a ] that is not captured (lookahead).

Alternatively you can just capture what's between the square brackets:

\[(.*?)\]

and return the first captured group instead of the entire match.

Answer from cletus on Stack Overflow
Discussions

Using Regex to extract a string between two strings
I am trying to use the extract with Regex function to extract a string that is always sitting between two strings of texts that never change. Here are 3 examples I want {“key”:“1671291382053x721052777787162600”} to return 1671291382053x721052777787162600 I want {“key”:“167112... More on forum.bubble.io
🌐 forum.bubble.io
8
0
December 19, 2022
RegEx, matching between two characters
You've already added a capturing group so just use match.Groups[1] to get the inside of the brackets. More on reddit.com
🌐 r/learncsharp
22
5
May 18, 2022
java - How to get a string between two characters? - Stack Overflow
This may help for more complex regex problems where you want to get the text between two set of characters. ... The other possible solution is to use lastIndexOf where it will look for character or String from backward. More on stackoverflow.com
🌐 stackoverflow.com
August 7, 2016
php - Regex, get string value between two characters - Stack Overflow
I'd like to return string between two characters, @ and dot (.). I tried to use regex but cannot find it working. (@(.*?).) Anybody? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Snowflake Community
community.snowflake.com › s › article › How-to-fetch-a-string-between-2-slashes-using-regular-expressions
How to fetch a string between 2 characters using regular expressions
Explanation: The above expression is looking for slash (/) and then captures all the non-slash characters (^) and ends before the next slash(/).
🌐
Bubble
forum.bubble.io › need help
Using Regex to extract a string between two strings - Need help - Bubble Forum
December 19, 2022 - I am trying to use the extract with Regex function to extract a string that is always sitting between two strings of texts that never change. Here are 3 examples I want {“key”:“1671291382053x721052777787162600”} to return 1671291382053x721052777787162600 I want {“key”:“1671128263833x743710543152935700”} to return 1671128263833x743710543152935700 I want {“key”:“1671128291585x470773579005820900”} to return 1671128291585x470773579005820900 When using this regex pattern {“key”:“(.*)”} with this...
🌐
GitHub
gist.github.com › vxhviet › 6533c0be8ccc310edb4b10d90d0d383b
Regular Expression to find a string included between two characters while EXCLUDING the delimiters · GitHub
Regular Expression to find a string included between two characters while EXCLUDING the delimiters · Raw · regex.md · Source: StackOverflow · Question: Regular Expression to find a string included between two characters while EXCLUDING the delimiters · Answer: Easy done: (?<=\[)(.*?)(?=\]) Technically that's using lookaheads and look behinds.
🌐
Regex Tester
regextester.com › 96872
Extract String Between Two STRINGS - Regex Tester/Debugger
Regex Tester is a tool to learn, build, & test Regular Expressions (RegEx / RegExp). Results update in real-time as you type. Roll over a match or expression for details. Save & share expressions with others. Explore the Library for help & examples. Undo & Redo with {{getCtrlKey()}}-Z / Y. Search for & rate Community patterns. ... extended (x) extra (X) single line (s) unicode (u) Ungreedy (U) Anchored (A) dup subpattern names(J) ... Url checker with or without http:// or https:// Match string not containing string Check if a string only contains numbers Only letters and numbers Match elements
Find elsewhere
🌐
TypeOfNaN
typeofnan.dev › how-to-capture-between-two-characters-in-javascript-using-regex
How to Capture Between Two Characters in JavaScript using Regular Expressions | TypeOfNaN
January 1, 2021 - Today we’ll use regex to capture all content between two characters. ... First off, we’ll want to use the JavaScript String match method, which takes a string or regular expression as an argument. const str = 'Hi there, my name is [name], I am [age] years old, and I work in the field of [profession].'; const matches = str.match(/some regex here/); We want to capture between the brackets. Our first go at this might include a regex that looks like this: /\[.+?\]/g. If we use this, we get the following:
🌐
Reddit
reddit.com › r/learncsharp › regex, matching between two characters
r/learncsharp on Reddit: RegEx, matching between two characters
May 18, 2022 -

So this one:(@"\[(.*?)]")

Matches everything between [ ] (INCLUDING the squared brackets).

But what if i DON'T want to include the squared brackets, so its ONLY what is in between them that must be matched?

Thank you in advance.

And thank you to the kind person in here who recommended "Exercism", what a great site with many good exercises in C#.

EDIT: Lots of great answers. Really appreciated, I also have to admit i clearly lacked basic understanding of RegEx.
I also realize that I used groups etc. without a need i guess.

What i wanted to match in a sentence like this:
[hello] mother.
Or a sentence like this:
[car] Mazda

was the inside of the brackets, so :
[hello] mother.
[car] Mazda

With my RegEx code it would match:

[hello] mother.

which i was not interested in.

🌐
Laserfiche Answers
answers.laserfiche.com › questions › 211802 › Regular-Expression-to-extract-string-between-two-strings
Regular Expression to extract string between two strings - Laserfiche Answers
September 13, 2023 - Can anyone give me some tips on how I can pull text between two texts? The expression I currently have only takes whatever comes after the first text [\s|\n|\r|\v|\f|\t]*([^\n]+) In my example below, I would like to pull the text between Reference #: and Urgency:, which is supposed to be blank. Any tips would be greatly appreciated, thank you! ... That's because parentheses are reserved characters for regular expressions and you need to escape them if you want them treated as "normal" parentheses.
🌐
ASPSnippets
aspsnippets.com › questions › 174452 › Extract-string-between-two-characters-using-Regular-Expression-in-ASPNet
Extract string between two characters using Regular Expression in ASPNet
protected void Page_Load(object sender, EventArgs e) { string input = "Drink: Fanta Strawberry + 0.00 USD <br/> Side: Classic chips + 0.00 USD <br/> "; input += "Option 1: Asian Ginger Chicken Egg Roll + 0.00 USD <br/> "; input += "Option 2: Chipotle Chicken Egg Roll + 0.00 USD <br/> "; input += "Option 3: V Greens and Cornbread Egg Roll + 0.00 USD <br/>"; string[] result = Regex.Matches(input, @"\:(.+?)\+").Cast<Match>().Select(s => s.Groups[1].Value.Trim()).ToArray(); Response.Write(string.Join(" ", result)); }
🌐
regex101
regex101.com › library › T7scY8
regex101: Extract String Between Two Strings
RegEx email /^((?!\.)[\w-_.]*)(@\w+)(\.\w+(\.\w+)?)$/gim; Just playing with Reg Ex. This to validate emails in following ways The email couldn't start or finish with a dot The email shouldn't contain spaces into the string The email shouldn't contain special chars ( mailname@domain.com First group takes the first string with the name of email \$1 => (mailname) Second group takes the @ plus the domain: \$2 => (@domain) Third group takes the last part after the domain : \$3 => (.com)
Top answer
1 of 16
1071

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

2 of 16
290

Lazy Quantifier Needed

Resurrecting this question because the regex in the accepted answer doesn't seem quite correct to me. Why? Because

(?<=This is)(.*)(?=sentence)

will match my first sentence. This is my second in This is my first sentence. This is my second sentence.

See demo.

You need a lazy quantifier between the two lookarounds. Adding a ? makes the star lazy.

This matches what you want:

(?<=This is).*?(?=sentence)

See demo. I removed the capture group, which was not needed.

DOTALL Mode to Match Across Line Breaks

Note that in the demo the "dot matches line breaks mode" (a.k.a.) dot-all is set (see how to turn on DOTALL in various languages). In many regex flavors, you can set it with the online modifier (?s), turning the expression into:

(?s)(?<=This is).*?(?=sentence)

Reference

  • The Many Degrees of Regex Greed
  • Repetition with Star and Plus
🌐
RegExr
regexr.com › 38prd
string between two strings
Supports JavaScript & PHP/PCRE RegEx.
Top answer
1 of 12
251

A lookahead (that (?= part) does not consume any input. It is a zero-width assertion (as are boundary checks and lookbehinds).

You want a regular match here, to consume the cow portion. To capture the portion in between, you use a capturing group (just put the portion of pattern you want to capture inside parenthesis):

cow(.*)milk

No lookaheads are needed at all.

2 of 12
148

Regular expression to get a string between two strings in JavaScript

The most complete solution that will work in the vast majority of cases is using a capturing group with a lazy dot matching pattern. However, a dot . in JavaScript regex does not match line break characters, so, what will work in 100% cases is a [^] or [\s\S]/[\d\D]/[\w\W] constructs.

ECMAScript 2018 and newer compatible solution

In JavaScript environments supporting ECMAScript 2018, s modifier allows . to match any char including line break chars, and the regex engine supports lookbehinds of variable length. So, you may use a regex like

var result = s.match(/(?<=cow\s+).*?(?=\s+milk)/gs); // Returns multiple matches if any
// Or
var result = s.match(/(?<=cow\s*).*?(?=\s*milk)/gs); // Same but whitespaces are optional

In both cases, the current position is checked for cow with any 1/0 or more whitespaces after cow, then any 0+ chars as few as possible are matched and consumed (=added to the match value), and then milk is checked for (with any 1/0 or more whitespaces before this substring).

Scenario 1: Single-line input

This and all other scenarios below are supported by all JavaScript environments. See usage examples at the bottom of the answer.

cow (.*?) milk

cow is found first, then a space, then any 0+ chars other than line break chars, as few as possible as *? is a lazy quantifier, are captured into Group 1 and then a space with milk must follow (and those are matched and consumed, too).

Scenario 2: Multiline input

cow ([\s\S]*?) milk

Here, cow and a space are matched first, then any 0+ chars as few as possible are matched and captured into Group 1, and then a space with milk are matched.

Scenario 3: Overlapping matches

If you have a string like >>>15 text>>>67 text2>>> and you need to get 2 matches in-between >>>+number+whitespace and >>>, you can't use />>>\d+\s(.*?)>>>/g as this will only find 1 match due to the fact the >>> before 67 is already consumed upon finding the first match. You may use a positive lookahead to check for the text presence without actually "gobbling" it (i.e. appending to the match):

/>>>\d+\s(.*?)(?=>>>)/g

See the online regex demo yielding text1 and text2 as Group 1 contents found.

Also see How to get all possible overlapping matches for a string.

Performance considerations

Lazy dot matching pattern (.*?) inside regex patterns may slow down script execution if very long input is given. In many cases, unroll-the-loop technique helps to a greater extent. Trying to grab all between cow and milk from "Their\ncow\ngives\nmore\nmilk", we see that we just need to match all lines that do not start with milk, thus, instead of cow\n([\s\S]*?)\nmilk we can use:

/cow\n(.*(?:\n(?!milk$).*)*)\nmilk/gm

See the regex demo (if there can be \r\n, use /cow\r?\n(.*(?:\r?\n(?!milk$).*)*)\r?\nmilk/gm). With this small test string, the performance gain is negligible, but with very large text, you will feel the difference (especially if the lines are long and line breaks are not very numerous).

Sample regex usage in JavaScript:

//Single/First match expected: use no global modifier and access match[1]
console.log("My cow always gives milk".match(/cow (.*?) milk/)[1]);
// Multiple matches: get multiple matches with a global modifier and
// trim the results if length of leading/trailing delimiters is known
var s = "My cow always gives milk, thier cow also gives milk";
console.log(s.match(/cow (.*?) milk/g).map(function(x) {return x.substr(4,x.length-9);}));
//or use RegExp#exec inside a loop to collect all the Group 1 contents
var result = [], m, rx = /cow (.*?) milk/g;
while ((m=rx.exec(s)) !== null) {
  result.push(m[1]);
}
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Using the modern String#matchAll method

const s = "My cow always gives milk, thier cow also gives milk";
const matches = s.matchAll(/cow (.*?) milk/g);
console.log(Array.from(matches, x => x[1]));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
UiPath Community
forum.uipath.com › help
How to Extract string between two strings? - Help - UiPath Community Forum
August 26, 2020 - I have a regex below that extract data between two strings , but I also want to exclude some text in between for example if there is a text “helloworld” in between two strings then I wanna exclude it. Any idea thanks System.Text.RegularExpressions.Regex.Match(strInput,"(?