Postive Lookahead substring regex

I am new to regular expressions, and the more I use them, the more I like them. I am working on a regular expression that must satisfy the following conditions:

  • Need to start with the Alpha character.
  • Of the following three characters, at least one must be an alpha character.
  • Anything after the first four characters is an automatic match.

I currently have the following regular expression: ^[a-zA-Z](?=.*[a-zA-Z]).{1}.*$

The problem I am facing is that my positive lookahead (?=.*[a-zA-Z]).{1} not limited to the next three characters following the alpha character.

It seems to me that there is no concept. What am I missing in this expression?

Thanks to everyone.

+4
source share
4 answers

.* does it in your search. You must limit the range here, for example

 ^[a-zA-Z](?=.{0,2}[a-zA-Z]).{1}.*$ 

Change If you want to make sure that there are at least 4 characters in a string, you can use a different view:

  ^[a-zA-Z](?=.{3})(?=.{0,2}[a-zA-Z]).{1}.*$ 
+3
source

What do you want to see? Why not just use

 ^[a-zA-Z](..[a-zA-Z]|.[a-zA-Z].|[a-zA-Z]..) 

and be happy?

+3
source

You may have to make a workaround. Sort of:

 ^[az](?=([az]..|.[az].|..[az])).{3}.* 
  • First char [az]
  • Positive appearance - the first or second or third char - az ([az]..|.[az].|..[az])
  • Other things
+1
source

Change * in your lookahead to ? to get m/^[a-zA-Z](?=.?[a-zA-Z]).{1}.*$

If I understand your criteria, this corrects it due to a change in greed.

They are correctly mapped:

 a2a3-match 2aaa-no match Aaaa-match a333-no match 
0
source

Source: https://habr.com/ru/post/1311864/


All Articles