Reputation: 23
I need a regular expression to get the text out from between [
and ]
within a sentence.
Example Text:
Hello World - Test[**This is my string**]. Good bye World.
Desired Result:
**This is my String**
The regex that I have come up with is Test\\[[a-zA-Z].+\\]
, but this returns the entire **Test[This is my string]**
Upvotes: 2
Views: 73
Reputation: 520
Match m = Regex.Match(@"Hello World - Test[This is my string]. Good bye World.",
@"Test\[([a-zA-Z].+)\]");
Console.WriteLine(m.Groups[1].Value);
Upvotes: 2
Reputation: 24806
You could use a capturing group to access to the text of interest:
\[([^]]+)\]
A quick proof of concept using JavaScript:
var text = 'Hello World - Test[This is my string]. Good bye World.'
var match = /\[([^\]]+)\]/.exec(text)
if (match) {
console.log(match[1]) // "This is my string"
}
If the regular expression engine you are using supports both lookahead and lookbehind, Tim's solution is more appropriate.
Upvotes: 2
Reputation: 336218
(?<=Test\[)[^\[\]]*(?=\])
should do what you want.
(?<=Test\[) # Assert that "Test[" can be matched before the current position
[^\[\]]* # Match any number of characters except brackets
(?=\]) # Assert that "]" can be matched after the current position
Read up on lookaround assertions.
Upvotes: 1