Hey everyone,
I'm trying to get my head around regex, specifically with the code I've been working on:
```javascript
const str = "abc123def";
const regex = /[a-z]+/;
const result = str.match(regex);
console.log(result);
```
I understand that **[a-z]** represents any lowercase letter from a to z and the **+** quantifier means to repeat the previous element one or more times. But I'm confused! Shouldn't that allow it to repeat the letters infinitely? Why does it only match **abc**?
Thanks for your help!
4 Answers
The key here is that the **+** operator is repeating the character class **[a-z]**, which means it will keep matching any lowercase letters until it hits a character that doesn't fit that class. So, in your example, it grabs **abc** first, then when it encounters **1**, which is not a lowercase letter, it stops there. That’s why it matches just **abc**!
Remember, the regex only matches letters from **a** to **z**. When it encounters characters like **1**, it won't count them and that's why it stops after matching **abc**. Think of it as a filter!
Yep, that's right! Your regex is only looking for those lowercase letters. As soon as it hits **1**, it breaks the match because that's outside the range defined in your regex. Simple as that!
If you want the regex to match all occurrences of lowercase letters in your string, you should use the global flag like this:
```javascript
const regex = /[a-z]+/g;
```
In that case, it would match **abc** and **def** separately if you check for matches multiple times!
Good point! With the global flag, you get all the matches instead of stopping at the first one.
Exactly! Once it hits numbers or any other characters, it halts the match. It's all about what fits in the brackets.