1

One of our clients have asked us to replace the first line break (&#xa) with a comma.

So far the regex that we have for our location address is this:

Location = vacancy.Location.IsNullOrEmpty() ?
        string.Empty :
        Regex.Replace(vacancy.Location, "&#?[a-z0-9]+;", " ");

Can someone tell me how i can add another rule to the regex pattern which would replace only the first instance of &#xa with a comma?

Thank you!

1 Answer 1

2

To answer your question specifically: Regex.Replace(vacancy.Location, "(?<!&#xa;.*)&#xa;", ", "), where (?<!&#xa;.*) is a negative lookbehind assertion.

However, my recommendation is to avoid regex in favor of more readable methods such as:

ReplaceFirstOccurrence(vacancy.Location, "&#xa;", ", ");

private static string ReplaceFirstOccurrence(string source, string find, string replace)
{
    int firstOccurrenceIndex = source.IndexOf(find);

    if (firstOccurrenceIndex < 0)
    {
        return source;
    }

    string resultAfterRemoval = source.Remove(firstOccurrenceIndex, find.Length);
    string resultAfterInsertion = resultAfterRemoval.Insert(firstOccurrenceIndex, replace);

    return resultAfterInsertion;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.