Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline regex layout

I have a regex: Regex("((group1)(group2))(group3)")

I'd like to format it in a way that looks nice and clear, i.e.:

(
  (group1)
  (group2)
)
(group3)

For example I've tried this:

Regex("("
    +   "(group1)"
    +   "(group2)"
    + ")"
    + "(group3)")     //--> loses the syntax highlighting in Intellij and a bit messy

Regex("""(
           (group1)
           (group2)
         )
         (group3)""") //--> not bad, but not equivalent (adds spaces and \n characters)

Is there a way to have a clean layout while keeping the regex equivalent to the original and the syntax highlighting?

like image 699
assylias Avatar asked Aug 30 '26 01:08

assylias


1 Answers

It looks like you still can use the COMMENTS modifier (or (?x) inline version):

Regex("""(?x)(          # Group 1
              (group1)  # Group 2
              (group2)  # Group 3
             )
             (group3)  # Another group"""

See COMMENTS RegexOption reference:

Permits whitespace and comments in pattern.

The # symbols must be escaped if they denote a literal # symbol in the pattern.

Note that literal spaces are also considered to be formatting whitespace, even inside character classes. Escape them if you need to match a literal space: """(?x)free\ spacing""" or """(?x)[a-zA-Z\ ]+""".

like image 194
Wiktor Stribiżew Avatar answered Sep 01 '26 14:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!