I’ve learned a whole lot about regular expressions over the last year and a bit, and there are two ‘phrases’ for lack of a better term that are sort of like the nuclear option or like a blunt object, but will get me most of where I need to go.
This is one of the most useful regular expression ‘phrases’ I’ve learned. It selects zero or more of any kind of character, including spaces, but isn’t greedy. (That just means that it’ll stop the first time it sees whatever is put after the question mark). The key limitation of this phrase is that it will not include new lines (though the exact implementation varies from language to language).
Related to the first phrase, this one selects one or more of any kind of character, including spaces, but isn’t greedy. This is useful when something has to exist, but can be any number of things. Like the one before it, this (usually) doesn’t include new lines.
This ‘phrase’ is even more ‘powerful’ than the one above. This one selects zero or more of any kind of character, including all kinds of whitespace (yes, also new lines), but again, isn’t greedy. I used this one a LOT for a while, especially in Java.
I was having trouble getting a regular expression to select an section of HTML that was broken up onto different lines irregularly 1. Finally I figured out that I wanted to use
\s*? (zero or more whitespace characters, not greedy) to account for the different amounts of spacing, but not to pick up any letters or other characters.
- yes, I know regex is not the tool of choices for HTML, but my hands were a bit tied on this project ↩