Home > other >  How would you retrieve N characters using regex from an existing regex?
How would you retrieve N characters using regex from an existing regex?

Time:06-24

I would need to retrieve an email id from a email address. (i.e. [email protected] => this-is-the-best-email)

The regex that I used is (.*)@.* .

Now I need truncate the string with N characters. (i.e. N=7 => this-is )

How would I add this to a existing regex? Any other recommendations?

CodePudding user response:

What about: ([^@]{1,7}). ?

[email protected]
[email protected]

Becomes:

this-is
short

CodePudding user response:

I think that this is what you are looking for:

((.{1,7}).*)@. 

The first capturing group contains the full id and the second group contains up to 7 chars.

CodePudding user response:

In your pattern (.*)@.* you don't need the trailing .* as it is optional, and the dot can match any character including spaces and the @ itself which can match much more that just an email like address.


The thing of interest is the non whitespace chars excluding an @ char before actually matching the @, and in that case you can use a capture group matching 7 non whitespace chars.

([^\s@]{7})[^\s@]*@

The pattern matches:

  • ([^\s@]{7}) Capture group 1, match 7 non whitespace chars excluding @
  • [^\s@]* Optionally match any non whitespace char excluding @
  • @ Match literally

Regex demo

  • Related