Question: I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.

I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>

The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`

Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.

Can someone steer me in the right direction?

Edit:

I want to match:

`test_handle`

`test.handle`

`testhandle`

`test_._handle`

Don't want to match:

`Test_handle`

`test_Handle`

`test__handle`

`test..handle`

`TESTHANDLE`

an

Answer: 
There are a number of things going on in the regular expression you're starting from:

```
^           # beginning of line
(?!.*\.\.)  # negative lookahead that effectively prevents double periods
(?!.*\.$)   # negative lookahead that prevents a period as the last character
[^\W]       # first character must be a word character
[\w.]{0,29} # from 0 to 29 word characters or periods
$           # end of line

```

Additionally, based on what I'm seeing in that link, it has three flags applied: `i`, `g` and `m`. The only one of consequence really is `i`, because that means case-insensitive search. If you're trying to modify it to be case sensitive, the first thing you'll need to do is remove that.

The `\w` or word metacharacter matches `a-z`, `A-Z`, `0-9`, and `_`. So if you want to restrict that, replace it explicitly with the characters you want to allow, resulting in:

```
^(?!.*\.\.)(?!.*\.$)[^\W][a-z_.]{0,29}$

```

Now, it mostly works except that the first character can still be a capital letter. The `[^\W]` portion essentially matches "NOT NOT a word character" or.. "a word character", which includes uppercase letters. I'm honestly not sure the rationale behind this. But if it's no difference to you, you can probably just remove it and increase the remaining character range to 30 to still allow for up to 30 characters leaving us finally with:

```
^(?!.*\.\.)(?!.*\.$)[a-z_.]{0,30}$

```

**Edit**:

As noted by David, I did not catch your requirement to disallow multiple underscores.. be sure to include his added backreference to account for this:

```
^(?!.*\.\.)(?!.*__)(?!.*\.$)[a-z_.]{0,30}$

```
Try this regex:

```
^(?!.*\.\.)(?!.*__)(?!.*[A-Z])(?!.*\.$)[^\W][\w.]{0,29}$

```

[RegExr demo](https://regexr.com/453us)

I've added this negative lookahead to disallow uppercase characters:

```
(?!.*[A-Z])

```

And this one to disallow double underscores:

```
(?!.*__)

```

---

One other important thing to remember is to uncheck the case insensitive flag.

[![enter image description here](https://i.stack.imgur.com/imOfP.png)](https://i.stack.imgur.com/imOfP.png)