0

I am programmatically generating a very lengthy regex expression in a lua script I'm developing. It works, but at 960 characters, I can't help thinking it can be simplified a bit. However, I can't think of a way to do that without breaking it. In a nutshell, it looks for a string of 1 or more space-separated predefined keywords. A much-shortened version of the regex looks like this. You can see the major portion of it, the keyword list, is repeated.

\(big\|hairy\|regex\)\( \+\(big\|hairy\|regex\)\)*

To remove the duplication, I could use this one. The problem here is that the string starts with a space; whereas, I need it to start with any of the keywords.

\( \+\(big\|hairy\|regex\)\)\+

Of course the next regex doesn't work because \1 refers to the text that was matched and not the regex that found it.

\(big\|hairy\|regex\)\( \+\1\)*

Can the regex be written so that the keyword list appears only once, but still matches correctly?

2
  • Does size really matter if you are generating it programmatically? No one will read it so why bother? Performance?
    – romainl
    Feb 18 at 14:06
  • Actually, I was having performance issues at one point. I solved that by adding \%#=1 to the beginning to use the old regex engine. I'll revisit that when I try Vivian's suggestion.
    – Phil R
    Feb 19 at 4:45

1 Answer 1

1

I would do:

 *\zs\( *\<\(big\|hairy\|regex\)\>\)\+

That I would rewrite:

\v *\zs( *<(big|hairy|regex)>)+

The first * eat the leading spaces if any.

They will not be part of the matching string because of the \zs that define the start of the matching.

The repetition don't force a set of between the keywords but because of the < and > you are forced to have at least a non word but because only are authorized in the regex you should have the desired result.

2
  • 1
    This is perfect. I even was able to remove the regex engine selection: \%#=1, mentioned in the comment above. Nice suggestion to use the \v flag too. It's much more readable now. Thanks, Vivian.
    – Phil R
    Feb 19 at 6:39
  • You are welcome! Thanks for the feedback :-) Feb 19 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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