.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

regex replace - but with a few exceptions.

Posted By:      Posted Date: September 26, 2010    Points: 0   Category :.NET Framework

I have a string containing HTML and I need to replace some words to be links (I know, working with regex against HTML is not accepted by all developers, but I cannot see an easy solution with any other technique) - I do this with the following code;

string lNewHTML = Regex.Replace(lOldHTML, "(\bword1\b|\bword2|word3\b)", "<a href=\"page.aspx#$1\">$1</a>", RegexOptions.IgnoreCase);

The code works, but I need to include some exceptions to the replace - e.g. I will not replace anything i an img-, li- and a-tag (including link-text and attributes like href and title) but still allow replacements in p-, td- and div-tags.

By using the following code I can avoid replacing in attributes;


But with the above code it still replaces words in e.g. links and headlines which is a no-go.

The last example I have seems to do what I need - but if my HTML-string contains more than a few characters my application crashes;


Can anyone figure out a solution to this?

View Complete Post

More Related Resource Links

Regex.replace [h2] to


I try to replace [h2] to <h2>
I use this coding:

string o = "<h2>test</h2>";
o = Regex.Replace(o, "[h2]", "<h2>");
o = Regex.Replace(o, "[/h2]", "</h2>");


But the result after the first regex is:


So that is not what i want.
After the first 1, he should make:


Whats wrong?

Replace space from string - REGEX.



I have some problem with RegEx.

I have text:

"something here [tagQuote=Name of Author]bla bla bla[/tagQuote] something here"

And now I want to replace all the whitespace character in quote attribute with "%#%#%#%".

So I want to have: [tagQuote=Name%#%#%#%of%#%#%#%Author]bla bla bla[/tagQuote]

So remove all of the whitespaces between "[tagQuote=" and "]...[/tagQuote]"

Need Regex.Replace help for lowercase to uppercase



I need help with Regex replacement.  I searched the web and tried for several hours but I just can't get it working. 

In theory, what I need to do is simple: make sure all element names in HTML tags are uppercase, e.g.:




If anyone could help me out I would greatly appreciate it!  


Regex with exceptions to check incorrect punctuation


Hi to all,

I'm faced with the following problem:

I need to check a punctuation rule in a large amount of text. For this purpose, I want to find all occurances of a word which is NOT preceded by a comma.

The grammatical rule states that the words XYZ, UVW, QRS  must be preceded by a comma, exluding the cases when they are preceded by the words ABC, DEF, GHI, in which cases the comma is not necessary.

1. Lorem ipsum nam ne xyz fuisset efficiantur voluptatibus, albucius molestie neglegentur cu quo. - must be matched because xyz is NOT preceded by a comma
2. Lorem ipsum nam ne, xyz fuisset efficiantur voluptatibus, albucius molestie neglegentur cu quo. - must NOT be matched because xyz is preceded by a comma
3. Lorem ipsum nam ne abc xyz fuisset efficiantur voluptatibus, albucius molestie neglegentur cu quo. - must NOT be matched because xyz is preceded by abc and the comma is omitted correctly
4. Lorem ipsum nam ne, abc xyz fuisset efficiantur voluptatibus, albucius molestie neglegentur cu quo. - must be matched because xyz is preceded by abc but the comma is NOT omitted

Can anyone help me to construct a regex that satisfies the above conditions - with and without lookarounds, if it's possible?

Thank you very much in advance!

Using Regex.Replace



I am reading in a file and performing a search & replace for specific matches. 

Is it possible to do the following with regular expressions? NOTE: the comma and slash being inserted in the output.

strLine = Regex.Replace(strLine, "<?data [REGEX HERE]?>", "<?data,\...\?>");

Input:  <?data ...?>

Output: <?data,\...\?>


RegEx.Replace - why is capture group 1 empty?


Using PowerShell to illustrate:

$t = '<img src="r1.jpg" width="330" class="image">'
$pattern = 'src[\s]*?=[\s]*?[''|"](.+?jpg)[''|"][\s]*?width=[''|"]330[''|"]'

[RegEx]::Match($t, $pattern)


Groups   : {src="r1.jpg" width="330", r1.jpg}
Success  : True
Captures : {src="r1.jpg" width="330"}
Index    : 5
Length   : 24
Value    : src="r1.jpg" width="330"

Just to confirm,


gives: r1.jpg



RegEx to get links attributes in order to replace


I have anchor tags which are unusually formatted.

I firstly I have tags which are as below <a name="1">text</a>

I need to get the value from the name attribute.

I then need to get the whole 1st part of the tag <a name="1"> so I can replace it with a properly formated tag i.e. <a href="URL" name="1">

I am a little lost in the world of Reg Ex and all the examples presume that there is a "href" followed by a formatted URL present.


As you can see I have to c# code to replace the regex output but just dont know where to start with the pattern.

public String replaceID_withLinksrcs(String Text, IRepository<Corp.Web.Model.Link> objLinks)
String parsedtext;
parsedtext = Text.Replace("shape=\"rect\"","");
String t18 = @parsedtext;
String p18 = @"/<^a name= $>";
t18 = Regex.Replace(t18, p18, new MatchEvaluator(delegate(Match match) { return MyLinkURLS(match, objLinks); }));
return t18;


How to get more information about the exceptions that can happen in SharePoint 2010 projects?

In case there is an exception anywhere in the SharePoint 2010 project (most common place an exception would happen is during deployment of your SharePoint project, custom deployment configuration or custom deployment steps), there's a registry key EnableDiagnostics available for you to use.

Can I replace the EntityObject as base-class in Entity Designer 3.5 sp1?


I'm using EF3.5sp1 for a project, and I've been working around many of its problems... as such, my entity partial classes have a lot of logic in them for change-tracking and whatnot.  Obviously, I'd like to factor this logic out into a common base class, but of course all my objects must derive from EntityObject.  Is it possible to tell them to derive from some class of my own invention (which would actually likely derive from EntityObject themselves)?

I'd rather avoid editing the EDMX file unless the changes will be safe on entity-model-update, since I'm still making changes to the database schema in this early state of my project.


Also, is there any good workaround for the fact that the change isn't tracked when you change EntityReference.EntityKey?

Regex pattern for validating IPv6


Can anyone can make a regular expression pattern for validating IPv6 (not IPv4)?

Ipv6 has many formats and aliases. I tried making the pattern but written in a lot of codes (i'm not sure my code below will be 100% accepting valid formats and 100% declines invalid formats).


Handling external C++ exceptions


Hi. I'm working in a application that uses an external .Dll developed in C++ language. According the business rule, the .Dll can throws one exception if it found a error. My question is if it's possible handle or catch a exception throwed by the C++ dll? The try/catch doesn't works. Bellow there's the code I'm using to call the C++ dll.

        public extern static IntPtr LoadLibrary(string lpLibFileName);

        [DllImport("kernel32", CharSet = CharSet.Ansi)]
        public extern static IntPtr GetProcAddress(IntPtr hLibModule, string procName);

        public extern static bool FreeLibrary(IntPtr hLibModule);

        private delegate void DllMethodCallBack(string param1, string param2);

        public void CallDllMethod(string param1, string param2)

.NET Matters: Aggregating Exceptions


Exceptions in .NET are the fundamental mechanism by which errors and other exceptional conditions are communicated. This month's column provides information about how to aggregate exceptions to help manage a variety of scenarios in which multiple exceptions might result from one operation, including scenarios involving parallelism and concurrency.

Stephen Toub

MSDN Magazine August 2009

CLR Inside Out: Handling Corrupted State Exceptions


There's a danger in using one-size-fits-all exception handling, and you need to know how to avoid it by being as specific as possible about how you handle errors.

Andrew Pardoe

MSDN Magazine February 2009

Bugslayer: Minidumps for Specific Exceptions


This installment of Bugslayer covers the use of ADPlus to create a minidump of your Microsoft .NET Framework 2.0 pro¬cesses on specific exceptions.

John Robbins

MSDN Magazine November 2006

Bugslayer: Unhandled Exceptions and Tracing in the .NET Framework 2.0


By now, you've certainly heard about the big changes coming in Visual Studio® 2005, but when it's time to move your code over it will be the small things that trip you up. In this column, I want to cover two of the many excellent changes that you could easily overlook as you make the move to the new runtime and development tools.

John Robbins

MSDN Magazine July 2005

ADO.NET: Tackle Data Concurrency Exceptions Using the DataSet Object


ADO.NET provides many techniques for improving the performance of data-intensive applications and for making them easier to build. The DataSet, the hallmark of the ADO.NET object model, serves as a miniature, disconnected facsimile of a data source. While using the DataSet improves performance by reducing expensive trips to the database server, it also introduces the possibility of multiple users attempting to change the same data simultaneously, thereby generating data concurrency exceptions. This article examines the common causes behind data concurrency exceptions and presents techniques for overcoming them.

David Burgett

MSDN Magazine April 2003

.NET Exceptions: Make the Transition from Traditional Visual Basic Error Handling to the Object-Orie


If you're used to Visual Basic 6.0 and you're making the transition to Microsoft .NET, you will find that error handling is quite different from what you've used for years. Visual Basic .NET uses a more object-oriented solution to signaling and responding to unexpected problems while your program is running. This approach, called structured exception handling, has a number of advantages over the On Error statements provided in previous versions of Visual Basic. For instance, exceptions give you lots more information about exactly what went wrong in your app. To help you take advantage of this modern error handling paradigm, this article will show you how to raise and respond to exceptions, as well as how to create your own custom exception classes.

Jesse Liberty

MSDN Magazine November 2002

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend