Regex to get string between curly braces
If your string will always be of that format, a regex is overkill:
>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"
substring(1
means to start one character in (just past the first {
) and ,g.length-1)
means to take characters until (but not including) the character at the string length minus one. This works because the position is zero-based, i.e. g.length-1
is the last position.
For readers other than the original poster: If it has to be a regex, use /{([^}]*)}/
if you want to allow empty strings, or /{([^}]+)}/
if you want to only match when there is at least one character between the curly braces. Breakdown:
/
: start the regex pattern{
: a literal curly brace(
: start capturing[
: start defining a class of characters to capture^}
: "anything other than}
"
]
: OK, that's our whole class definition*
: any number of characters matching that class we just defined
)
: done capturing
}
: a literal curly brace must immediately follow what we captured
/
: end the regex pattern
Regex: Get anything between any curly braces
You may get the results you need using
var results = Regex.Matches(text, @"{({*[^{}]*}*)}")
.Cast<Match>()
.Select(x => x.Groups[1].Value);
See the regex demo.
Regex details
{
- an open curly brace({*[^{}]*}*)
- Group 1:{*
- 0 or more open curly braces[^{}]*
- 0 or more chars other than curly braces}*
- 0 or more close curly braces
}
- a close curly brace
regex - extract strings between curly braces without the curly braces
We can use a regex lookaround to match the {
as lookaround followed by one or more characters that are not a }
.
stringr::str_extract(text_test, '(?<=\\{)[^\\}]+')
#[1] "function_name" "function_title" "function_name"
Regex matches one or more characters that are not a }
([^\\}]+
) that follows a {
(regex lookaround ((?<=\\{)
)
In base R
, we can use regmatches/regexpr
regmatches(text_test, regexpr("(?<=\\{)[^\\}]+", text_test, perl = TRUE))
#[1] "function_name" "function_title" "function_name"
Regex to get string between curly bracket tags in PHP
You need to escape the braces, and use /s
to match more than single line. Below is the code example.
Code
<?php
$input = '
{list:start:Data}
{id} is having a title of {title}
{list:end:Data}
{list:start:Data1}
{id1} is having a title of {title1}
{list:end:Data1}
{list:start:Data2}
{id2} is having a title of {title2}
{list:end:Data2}
{list:start:Data3}
{id3} is having a title of {title3}
{list:end:Data3}
';
preg_match_all(
"/\\{list:start:(.+?)\\}(.*?)\\{list:end:(.+?)\\}/s",
$input,
$preg_matches
);
$matches = [];
foreach ($preg_matches[1] as $k => $v) {
$matches[] = [
"string" => trim($v),
"data" => trim($preg_matches[2][$k])
];
}
print_r($matches);
Output
Array
(
[0] => Array
(
[string] => Data
[data] => {id} is having a title of {title}
)
[1] => Array
(
[string] => Data1
[data] => {id1} is having a title of {title1}
)
[2] => Array
(
[string] => Data2
[data] => {id2} is having a title of {title2}
)
[3] => Array
(
[string] => Data3
[data] => {id3} is having a title of {title3}
)
)
Regex to match string between curly braces (that allows to escape them via 'doubling')
You can use
(?<!{)(?:{{)*{([^{}]*)}(?:}})*(?!})
See the .NET regex demo.
In C#, you can use
var results = Regex.Matches(text, @"(?<!{)(?:{{)*{([^{}]*)}(?:}})*(?!})").Cast<Match>().Select(x => x.Groups[1].Value).ToList();
Alternatively, to get full matches, wrap the left- and right-hand contexts in lookarounds:
(?<=(?<!{)(?:{{)*{)[^{}]*(?=}(?:}})*(?!}))
See this regex demo.
In C#:
var results = Regex.Matches(text, @"(?<=(?<!{)(?:{{)*{)[^{}]*(?=}(?:}})*(?!}))")
.Cast<Match>()
.Select(x => x.Value)
.ToList();
Regex details
(?<=(?<!{)(?:{{)*{)
- immediately to the left, there must be zero or more{{
substrings not immediately preceded with a{
char and then{
[^{}]*
- zero or more chars other than{
and}
(?=}(?:}})*(?!}))
- immediately to the right, there must be}
, zero or more}}
substrings not immediately followed with a}
char.
Regex: find string between curly brackets, which itself contains curly brackets
If there is no arbitrary nesting, you can use a pattern with negated }{
like
\\hyperlink{[^}{]*}{[^}{]*(?:{[^}{]*}[^}{]*)*}
Similar this answer but unrolled. See the demo at regex101. To {
extract}
use groups (demo).
Depending on your environment / regex flavor it can be necessary to escape the opening {
by a backslash for the braces that are not inside a character class to match them literally.
Further note that \S+
can consume }
and .+
can match more than desired if unaware.
Extract string between curly braces in java
There is an indexOf
method that takes the index from which to search
String str = "{a,b,c},{1,2,3}";
int startingIndex = str.indexOf("{");
int closingIndex = str.indexOf("}");
String result1 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result1);
startingIndex = str.indexOf("{", closingIndex + 1);
closingIndex = str.indexOf("}", closingIndex + 1);
String result2 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result2);
In the second block, we make the search start at closingIndex + 1
where closingIndex
is the index of the last seen }
.
Regular expression between curly braces, but ignore nested
This is a job for recursion.
If your regex flavour supports it, you can use:
(?<={)([^{}]++|\{(?1)\})+(?=})
Demo & explanation
Regex pattern to get string between curly braces
You can use this recursive regex pattern in PHP:
$re = '/( { ( (?: [^{}]* | (?1) )* ) } )/x';
$str = "The quick brown {fox, dragon, dinosaur} jumps over the lazy {dog, cat, bear, {lion, tiger}}.";
preg_match_all($re, $str, $matches);
print_r($matches[2]);
RegEx Demo
Related Topics
How to Hide the Address Bar on Iphone
How Exactly Use and Update the Global Variables in React-Native
Passing Multiple Parameters from Angular to Rest Service
Getting Internal Server Error (500) - Codeigniter
How to Render a Collection of Children Using Array
Convert 12-Hour Hh:Mm Am/Pm to 24-Hour Hh:Mm
Fetch - Missing Boundary in Multipart/Form-Data Post
Image Resizing Client-Side With JavaScript Before Upload to the Server
Refresh Page and Keep Scroll Position
How to Protect HTML Form from Blank Submission
How to Convert All Elements in an Array to Integer in JavaScript
Converting Byte Array to String in JavaScript
Observe Localstorage Changes in Js
How to Sort a Map by Value in JavaScript
How to Concatenate a Variable for a Hyperlink
Javascript Return True or Return False When and How to Use It