Home > Software engineering >  regex capture from fix length of string only N number of characters
regex capture from fix length of string only N number of characters

Time:12-14

i have fixed number of alphanumeric string i need to recognize the fixed length of the string and then capture only 8 characters of that string.
For example string : here i want to capture only the 10 length string which is :12345abcde
And from this string only 8 characters so the captured string be : 12345abc

"qqqq wwww123 12345abcde ddd33"

i managed only to capture the string it self like this :

(\w){10}

But how can i capture only 8 from this string ?

CodePudding user response:

Simple (\w{w})\w{2} won't work if there is a longer word in search text - you'll get it captured then too.

My first thought was to surround this with negative lookbehind and negative lookahead to ensure we are limiting the capture to 10 characters long string only (this will also work if the matched word is at the beginning or the end of the string):

(?<!\w)(\w{8})\w{2}(?!\w)
  • Related