Varun kumar
Varun kumar

Reputation: 3039

Regex for removing everything after a certain character only if the character occurs after a specific number of characters

I'm looking for a simple regular expression for this,

Example 1:

n = 5

Input: abcde@[email protected]

Output: abcde@varun

Example 2:

n = 5

Input: abcd@[email protected]

Output: abcd@[email protected] 

This means that if n = 5 and if the symbol @ is NOT occuring on or before the 5th index(Assuming the string starts at index 1) then remove all everything(including the @ symbol) after the second occurance of @.

Leave the string as it is if the above rule is not satisfied.

Thanks Varun.

Upvotes: 0

Views: 120

Answers (2)

vks
vks

Reputation: 67968

^(?!(?:@|.@|.{2}@|.{3}@|.{4}@))(.*?@.*?)@.*$

Try this.Replace by $1.See demo.

https://regex101.com/r/uC8uO6/7

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

You can use this regex to capture the part that you wish to keep into the first group:

(^[^@]{5,}@[^@]*)@

The expression matches a string that has at least two @ signs, with the first @ not occurring within the initial five characters.

This would capture abcde@varun, but not abcd@varun, because @ occurs within the initial five characters.

Demo.

Replace 5 with n to change the length of the prefix as needed.

Upvotes: 2

Related Questions