Extracting help from text using regex

Viewed 38

I have below text and I want to obtain certain parts from it.

Checkbox[Skip Transfer]: Skip the transfer process if checked.

Dropdown[OS Types]:     A dropdown to select the target OS. Transfer protocol,
                        connection protocol and destination path will be adjusted
                        based on this option.
                            * Destination path may be changed manually. If it was
                              changed this option has no effect on destination.
Dropdown[CPU Types]:    A dropdown to select the executable. Target file will be
                        adjusted based on this option.
                            * Source file may be changed manually. If it was
                              changed this option has no effect.
Dropdown[Copy Actions]: A dropdown to select the action that will be applied on the
                        destination file.

This is my help message and I want to pass related parts to the related items.

Checkbox[Skip Transfer]: Skip the transfer process if checked. For this line, Checkbox is my type, Skip Transfer is my text and Skip the transfer process if checked. is my help message for related item.

I tried following regex(in Python): (?P<kind>\w+)\[(?P<name>[\w ]+)\].*:\s+(?P<help_msg>[\w\W]*)(?!(\w+\[))

The kind and the name parsed successfully but I couldn't get the help message correctly.

2 Answers

Try with this:

(?P<kind>\w+)\[(?P<name>[\w ]+)\].*:\s+(?P<help_msg>(?:[^\n]|\n(?!\w+\[))*)

As help message I'm getting

  • all the characters that are not linebreaks AND
  • linebreaks that are not followed by your pattern \w+\[

See demo.

You could repeat all the lines using .* instead of [\w\W]* and then assert that it does not start with \w+\[ after matching a newline.

You could prevent some backtracking making use of a negated character class to match until the first occurrence of the colon using [^:]*:

(?P<kind>\w+)\[(?P<name>[\w ]+)][^:]*:\s+(?P<help_msg>.*(?:\r?\n(?!\w+\[).*)*)

In parts

  • (?P<kind>\w+) Named group kind, match 1+ word chars
  • \[ Match [
  • (?P<name>[\w ]+) Named group name, match 1+ times either or a word char
  • ][^:]*:\s+ match ], then 0+ times any char except : and then match : followed by 1+ whitespace chars
  • (?P<help_msg> Named group help_msg
    • .*(?:\r?\n(?!\w+\[).*)* Match all lines that do not start with \w+\[
  • ) Close group help_msg

Regex demo

Edit

The version without the negated character class that worked for the OP

(?P<kind>\w+)\[(?P<name>[\w ]+)].*:\s+(?P<help_msg>.*(?:\r?\n(?!\w+\[).*)*)

Regex demo

Related