So, as part of my application, I need it to read data from a text file, and get elements between curly brackets.
e.g:
Server_1 {
/directory1 /directory2
}
Server_2 {
/directory1
/directory2
}
Then something like, if Server == Server_1
, print the directories.
How are curly brackets used? Curly brackets are commonly used in programming languages such as C, Java, Perl, and PHP to enclose groups of statements or blocks of code.
To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.
The curly brackets are used to match exactly n instances of the proceeding character or pattern. For example, "/x{2}/" matches "xx".
Definition of curly brace : either one of the marks { or } that are used as a pair around words or items that are to be considered together.
You can try with this:
\{(.*?)\}
Explanation
\{ matches the character { literally (case sensitive)
(.*?) 1st Capturing Group
.*?
matches any character*?
Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)\}
matches the character }
literally (case sensitive)Sample Code to extract content inside curly bracket:
import re
regex = r"\{(.*?)\}"
test_str = ("Server_1 {\n"
"/directory1 /directory2\n\n"
"}\n"
"Server_2 {\n\n"
"/directory1\n\n"
"/directory2\n\n"
"}")
matches = re.finditer(regex, test_str, re.MULTILINE | re.DOTALL)
for matchNum, match in enumerate(matches):
for groupNum in range(0, len(match.groups())):
print (match.group(1))
Run the code here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With