-1

I have a string something like this,

Example 1 @abc@xy<a href="http://-example.com">-example.com</a> and @xyz@abc.com Example 2

Now, I want to remove the string occurring after the second @ encountered, i.e. @example.com @abc.com and preserve the rest of the data which should look like,

Example 1 @abc and @xyz Example 2

I have tried a lot of RegExp and saw many examples but have had no luck so far.

If anyone has tried something similar, it'd be great if you can help me out.

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37

4 Answers4

1

For the second half of your sample you can simply match both @s and replace only the second on, by grouping and using them in the replace.

Pattern: /(@[^\s@]*)@[^\s@]*/g Replacement: '$1'

This matches an @ followed by anything but spaces and @ and stores it in group 1. It then matches the next @ and again anythihng but spaces and @.

If there might be other stuff between both @s, you could adjust your pattern to use (@[^@]*) for the capturing group.

Four the first part of your sample, you would have to find a better pattern to match what follows the second @, this could be something along @[^\s@<]*(?:<[^<>]*>[^<>]*<\/[^<>]*>) but I'm not quite sure about your requirements and matching along tags is always tricky.

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37
0

Try this pattern: ^[^@]*@[^@]+(?=@). It will match everything before second @. It anchors at the beginning of a string, first it matches everything except @: [^@], then matches @, then again matches everything except @: [^@], until next @ is met: (?=@) (positive lookahead).

Demo

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

Capture the first @ followed by non-@ characters in a group, then match @ again followed by non-space characters, and replace with the first captured group:

(@[^@]+?)@[^ ]+?(?= )

Result:

Example 1 @abc and @xyz Example 2

https://regex101.com/r/mXRlsZ/1

Note that this will also replace any @s in a row, past the first - eg @abc@xy@foo will become @abc

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • You don't need all those non-greedy quantifiers and the positive lookahead: `(@[^@]+)@\S+` – revo Aug 10 '18 at 09:38
0
string input = @"Example 1 @abc@xy<a href=""http://-example.com"">-example.com</a> and @xyz@abc.com Example 2";
string pattern = @"@.+?(?=@|$)";
int x = 0;
string s = Regex.Replace(
    input,
    pattern,
    m => ++x == 2 ? Regex.Match(m.Value, @">(\s+.+?\s+)$").Groups[1].Value : m.Value);

Explanation

First, start with searching for @ symbol. Variable x is tracking the number of occurrences of @. As soon as it hits 2, then we extract everything between the end and >. If x doesn't equal to 2, then we just return the match (m.Value);

JohnyL
  • 6,894
  • 3
  • 22
  • 41