Using Regular Expressions is not easy. Mostly we have the feeling we need to learn a new language on the top of those we already know. But, the power and the flexibility that RegEx provides, make it worthy to learn. Take a look at some useful patterns, tools, and sources!
Matching all the words
Matching words in the given context can be complicated. Since many languages use special characters, mostly we can’t use any built-in function for that. Fortunately, we have the chance to build our character mapping with RegEx. Let’s see an example that is compatible with Hungarian:
Matching all the content between the specified tags
Often we need to capture the content between HTML tags. For example, when we are parsing some context – may be an input or maybe an HTML source from somewhere – we need the flexibility to extract what we need easily. Here is an example with <p> tags:
Also, we can make it dynamic. For example we want to get all the headers from <h2> to <h4>. Of course, we need to ensure we get the content between the opening and closing tag and not between an <h2> and an <h3> tag.
So, we define the first capturing group from 2 to 4. That means, only <h2>, <h3> and <h4> will be relevant. Then, we need them only if they have some content between the tags. In the end, we see the \1 numeric reference. It means we refer to the first capturing group’s result. This way our pattern can be dynamic.
Tools and Resources
Of course, these are only basic patterns. We just wanted to show how powerful can be a pure expression.
If you are interested in learning more about RegEx, we suggest the following resources:
- Understand Regular Expressions: https://laracasts.com/series/understanding-regular-expressions
- Regex tutorial — A quick cheatsheet by examples: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
- RegexOne: https://regexone.com/