Title: Regex taking a lot of time when tested with large data
Tags: java;regex
Question: I have created a java regex
```(?=\b((?<![^\p{Alnum}\p{Punct}])(?:\p{Alnum}+\p{Punct}\p{Alnum}+){2})\b)
```
I tested this regex against a sample string: https://www.google.com.google.com
It is giving me all the expected tokens:
```www.google.com google.com.google com.google.com
```
But, the issue with the above regex is that it is taking a lot of time when tested with a large string.
My expected tokens are in the form of &quot;alphanumeric punctuation alphanumeric&quot;.
How can I optimize this regex?

Comment: To check, do you want matches which are "alphanumeric punctuation alphanumeric" or strings which are made up of alphanumeric strings delimited by single punctuation characters (i.e. so you can have multiple `www.google.com` is valid as well as `www.google` being valid?  E.g. https://regex101.com/r/LVLTFg/1

Here is the accepted answer: You need to simplify the regex like this:
```(?=\b((?:\p{Alnum}+\p{Punct}){2}\p{Alnum}+)\b)
```
See the regex demo.
Details:

```\b``` - a word boundary
```((?:\p{Alnum}+\p{Punct}){2}\p{Alnum}+)``` - Group 1:

```(?:\p{Alnum}+\p{Punct}){2}``` - two occurrences of one or more letters/digits and a punctuation char and then
```\p{Alnum}+``` - one or more letters/digits


```\b``` - a word boundary

Note that each subsequent pattern does not match at the same location inside the string, which makes it as efficient as it can be (still, the overlapping patterns performance is not that great since they must evaluate each position inside the string, from left to right).

Comment for this answer: Thank you so much, Wiktor. Earlier, it was taking 2 mins 20 sec but, now it gave the result in 4 secs.
Comment for this answer: @DareToDead Patterns like `(a+ba+)+` are catastrophic backtracking prone. You can learn more about this in [this YT video of mine](https://www.youtube.com/watch?v=4-nrlRF5xX0). Although the regex described is an email validation pattern, you will see the similar approach.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:05/27/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><regex>', 'Title': 'Regex taking a lot of time when tested with large data', 'ViewCount': 50, 'id': 72402371, 'user_AboutMe': None, 'user_AccountId': 24831066.0, 'user_DisplayName': 'DareToDead', 'user_Reputation': 47.0, 'user_Views': 16.0, 'user_id': 18784920.0}}