155

I have this regex here;

\[sometag\](.*)\[/sometag\]

Which is supposed to catch text surrounded by the [sometag] tag. It works for single line information contained in these tags, like on the string [sometag]this is a bit of text[/sometag]. But it doesn't work on text that spans multiple lines, like this;

[sometag] here is more text

it spans more than one line [/sometag]

For some reason, Sublime text's regex finder won't recognize the tags across multiple lines. I want to know if this a problem with Sublime Text, a toggleable option, or just my personal incompetence with regexes.

2 Answers 2

288

At the start, use a dotall modifier (?s) to make dot to match also newline characters.

(?s)\[sometag\](.*?)\[\/sometag\]

DEMO

5
  • Thanks! Why do I have to include those extra question marks though?
    – Maurdekye
    Sep 30, 2014 at 15:21
  • 12
    ? after * will do a non-greedy match. Consider [b]foo[/b]foo[b]bar[/b] as example. \[b\].*\[\/b\] would match the whole from the starting b to the last closing b. Sep 30, 2014 at 15:23
  • just play with adding and removing the ? in this regex101.com/r/gI0xC3/2 Sep 30, 2014 at 15:26
  • 14
    (?s) causes the dot to also include newlines
    – cmroanirgo
    Feb 10, 2015 at 19:49
  • thansk god you exist. Ive always tried to do that in sublime but I could not because I though we could not use modifiers in sublime search/replace Nov 10, 2022 at 17:23
21

If modifying of dot's mode is inadmissible for some reasons, you may take that:

[sometag](.|\n)+?[/sometag]
2
  • 5
    Never use (.|\n)+? if you have an access to the DOTALL modifier. If you cannot use (?s) in some falvor, use [\s\S]/[\d\D]/[\w\W], but not the alternation patter suggested here. This pattern is highly inefficient and can easily lead to a timeout issue. May 17, 2016 at 12:03
  • 4
    @WiktorStribiżew: Can you explain why it is inefficient? I always use [\s\S], but at a glance (.|\n) would seem equivalent? Is it to do with matching groups? But then (?:.|\n) would be the same?
    – Cerberus
    May 2, 2019 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.