简体   繁体   中英

How to match text in […] with NSRegularExpression

what would be the NSRegularExpression to match the text between the "[" and the "]" in the following example:

"[this is some] text i would [like] to [parse] with NSRegularExpression"

Thx in advance :)

Like a Daniel answer right pattern is \\\\[(.*?)\\\\] Let me explain why.

  1. \\\\[ is mean "open-bracket" symbol. Double slash allow to use special symbol [
  2. All in ( ) allow to union as atomic sequence
  3. . — any symbol without special * ? + [ ( ) { } ^ $ | \\ . /! * ? + [ ( ) { } ^ $ | \\ . /!
  4. *? — symbol entry 0 or more times. Match as few times as possible.
  5. \\\\] — close-bracket

Not sure about NSRegularExpression, but I suspect it's like other regular expressions in terms of greediness. So, if there could be multiple [words] or [phrases in brackets] that you want to capture in the same string, you'll have to make sure the regex isn't greedy.

Maybe something like (broken up across a few lines for clarity:)

\[                     // find an opening square bracket
  ([^]]+)              // find one or more characters that ARE NOT a square bracket
\]                     // find the corresponding closing square bracket

您的模式应为\\[(.*?)\\]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM