كيف يمكنني استخراج كافة الرموز {} من سلسلة باستخدام التعابير المنطقية الصافية ل؟
سؤال
وأحتاج لاستخراج الرموز التي تم وضع علامة مع الأقواس من سلسلة معينة.
ولقد حاولت استخدام اكسبرسو لبناء شيء من شأنها أن تحليل ...
-------------------------------------------------------------
"{Token1}asdasasd{Token2}asd asdacscadase dfb db {Token3}"
-------------------------------------------------------------
ووإنتاج "Token1"، "Token2"، "Token3"
وحاولت استخدام ..
-------------------------------------------------------------
({.+})
-------------------------------------------------------------
و... ولكن على ما يبدو لتتناسب مع التعبير بالكامل.
وأي أفكار؟
المحلول
وحاول
\{(.*?)\}
The \{ will escape the "{" (which has meaning in a RegEx). The \} likewise escapes the closing } backet. The .*? will take minimal data, instead of just .* which is "greedy" and takes everything it can.
If you have assurance that your tokens will (or need to) be of a specific format, you can replace .* with an appropriate character class. For example, in the likely case you want only words, you can use (\w*) in place of the (.*?) This has the advantage that closing } characters are not part of the class being matched in the inner expression, so you don't need the ? modifier).
نصائح أخرى
وجرب:
\{([^}]*)\}
وهذا من شأنه كبح عملية البحث داخل متعرج تستعد لوقف على قوس الإغلاق.
وحل آخر:
(?<=\{)([^\}]+)(?=\})
وهذا يستخدم lookahead وlookbehind حتى لا تستهلك الأقواس على الإطلاق.
والأقواس مجعد لها معنى خاص في التعبيرات العادية، لذلك عليك ان يهرب منهم. استخدام \{
و\}
لمطابقتها.
لا تنتمي إلى StackOverflow