Click here to Skip to main content
15,886,788 members
Everything / General Programming / Regular Expressions

Regular Expressions

regular-expression

Great Reads

by Christoph Buenger
Describes PHP application development with the free Scavix Web Development Framework (Scavix-WDF).
by honey the codewitch
Build a feature rich, non-backtracking regular expression engine and code generator in C#
by honey the codewitch
Embed fast streaming C# code to match text based on inputted regular expressions
by Daniel Vaughan
A Visual Studio regex to remove someone's overzealous use of regions in VS. Find and replace: (^.*\#region.*$)|(^.*\#endregion.*$) Remember to enable regular expressions in the Visual Studio find and replace dialog.

Latest Articles

by honey the codewitch
How to validate fields for things like data entry applications.
by honey the codewitch
Easily add lexers to your project with this simple drop in NuGet package and a few annotations
by honey the codewitch
In this article, we explore the inner workings of Visual FA
by honey the codewitch
Continuing in the Visual FA series, now we explore API fundamentals

All Articles

Sort by Title

Regular Expressions 

27 Nov 2013 by LGSon2
UpdatedI need help with a regex that will find a "@[..[...]]" pattern.I will try to explain.----------------------A text will contain placeholders which will be replaced with values upon display of that very same text.A place holder has 3 parts;- an open tag, starts with "@["...
28 Nov 2013 by LGSon2
After struggling with google search and reading about balanced group I finally got things working, though I had to alter the pattern slightly to make it work, at least for me :)Regex: ...
30 Oct 2013 by Kyle A.B.
I have a regular expression that I need to match which searches for a Latitude Longitude point in a couple of different formats. The problem with this is that it will match partial coordinates out of numbers that shouldn't work as...
30 Oct 2013 by strogg
Try this instead of enclosing your exp with [^\d]...regex...[^\d](?
19 Nov 2013 by ♥…ЯҠ…♥
Hi Bala,Here is the regex for dollar symbol^([0-9]{1,3}\$?)$ (dollar optional here)If dollar mandatory at last with single appearance then use this ^([0-9]{1,3}\$)$ or ^([0-9]{1,3}\${1})$ (dollar mandatory here)will allow 100$, 111$, 001$, 123$.For indian currency you can...
19 Nov 2013 by bala_1990
I need a regex pattern for below words:100$₹100
5 Mar 2014 by Kurac1
Write a regular expression that can replace all emails in text with "[EMAIL]":"Christian has christian@email.com. Olof has the email olof@gmail.com. Lars has the emai britt123@oxford.co.uk."How should i do this?
5 Mar 2014 by Krunal Rohit
It's pretty simple, See the MSDN[^] documentation.-KR
5 Mar 2014 by Thomas Daniels
Try this:string textWithEmails = "Christian has christian@email.com. Olof has the email olof@gmail.com. Lars has the emai britt123@oxford.co.uk.";string filteredStr = Regex.Replace(textWithEmails,...
5 Jan 2011 by Keith Barrow
You asked this question Here How to get formatted output..???[^] do not repost. I am going to delete this question.
6 Jan 2011 by venkatrao palepu
string orderlist = "ONETWOTHREE";In this string, how to find howmany no.of 's ?Actually I want an output like this...?1. ONE2. TWO3. THREE
6 Jan 2011 by nagendrathecoder
You need to parse the string using those nodes, just like we do while deserializing an xml string.
6 Jan 2011 by OriginalGriff
Since this isn't quite a repost - just very, very, very nearly...You have been given a regex which returns the text content of the HTML. You just need to expand it to extract the text from the "li" section into separate matches, and then process them. Since you are only interested in the...
6 Jan 2011 by Hiren solanki
For finding no of li'sstring li = "ONETWOTHREE"; Regex regex = new Regex(@"li"); int count = regex.Matches(li).Count;For other stuff see OrginalGriff's answer.
22 May 2022 by Phoenix Liveon
A quick quest: We want the result looks like this; from aaa---bbb-ccc into aaa.bbb.ccc What I have tried: def objective = "aaa---bbb-ccc" objective.replace(/.*[-]+.*/, '.') How do we create a proper pattern of Regular expression in Groovy?
15 Apr 2022 by Patrice T
Did you tried this ? def objective = "aaa---bbb-ccc" objective.replace(/[-]+/, '.') Just a few interesting links to help building and debugging RegEx. Here is a link to RegEx documentation: perlre - perldoc.perl.org[^] Here is links to tools...
15 Apr 2022 by OriginalGriff
That's because you don't use the "non-hyphen" data in your replacement. Try this: (.*?)-+(.+?)-(.*) And this replacement string: $1.$2.$3
15 Apr 2022 by Phoenix Liveon
I found some answer and this is what its looks like we substitute method "replace" with "replaceALL"; def objective = "aaa---bbb-c" println( objective.replaceAll(/[-]+/, '.') )
20 Aug 2013 by Aarti Meswania
Hi experts,string Input = "@a = '1', @b = 'hello@123.com,hi@123.com'"I want to split Input string and want output as below using regexary[0] = a = '1'ary[1] = b = 'hello@123.com'I want to split by @ and it should not be in single quotesthanks in adv.
20 Aug 2013 by OriginalGriff
Don't use a regex, just use string.Split:string Input = "@a = '1', @b = 'hello@123.com,hi@123.com'"string[] ary = Input.Split(',');
20 Aug 2013 by Aarti Meswania
I got solution after some trial & error,Hope it will useful for people have same requirementstring Input = "@a = '1', @b = 'hello@123.com,hi@123.com'"string Output = Regex.Split(Input, @"(?=@\w+[ =|=])@")(condition)true|false(?=@\w+[ =|=]) condition @ if true then split...
7 Oct 2013 by Rakesh Meel
visit here..http://www.dotnetperls.com/regex-split[^]
24 Jan 2011 by cesimkaol
Hey people,I am confused by that example that was written for e-mail validation.Check it:Regex regex = new Regex(@".*@.{2,}\..{2,}");What is that {2,}?UPDATE: Resolved by OP himself.
24 Jan 2011 by cesimkaol
problem solved....2 denotes there minimum matchfor exampleRegex regex = new Regex(@".*@.{10,}\..{2,}");unforgiven@metallica.com metallica there is 9 character.its not gonna match.but it will be matched when Regex regex = new Regex(@".*@.{9,}\..{2,}") is...
13 Mar 2013 by Michael D Bray
Filling in text templates from a data source.
30 Aug 2013 by Member 10243871
'/^[a-z,ñ]+((-| )?[a-z,ñ]+)+((-| )?[a-z,ñ]+)?$/i'Why doesn't it accept if i only input 1 character?
30 Aug 2013 by OriginalGriff
Simple: you have told it not to!If I compact this a bit it may be a bit more obvious:^x+y+(z+)?$Where x, y, and z are the "phrases" in your regex.That requires "one or more x", then "one or more y", then "one or more z" - a minimum of three characters.I don't know exactly what you...
25 Sep 2011 by emrea
I'm not good at regular expressions. I try to filter texts in bracket,string temp="[Apple][Orange]Eating";I need a array fill of Apple and Orange, how can i do that?Regards
25 Sep 2011 by André Kraak
You can use the Regex.Split Method[^].Use these links to find out how regular expressions work:.NET Framework Regular Expressions[^]Regular Expression Language Elements[^]
25 Sep 2011 by Simon Bang Terkildsen
string inputString = "[Apple][Orange]Eating";MatchCollection matches = Regex.Matches(inputString, @"\[(?.+?)\]");string[] theArray = matches.Cast() .Select(m => m.Groups["content"].Value).ToArray();You can use Regex.Split instead of...
31 Mar 2019 by honey the codewitch
A Non-Backtracking Regular Expression Engine for .NET (Core)
2 Feb 2012 by cutexxbaby
how to change this regular expession to must have two decimal place((0)+(\.[1-9](\d)?))|((0)+(\.(\d)[1-9]+))|(([1-9]+(0)?)+(\.\d+)?)|(([1-9]+(0)?)+(\.\d+)?) cause i try 0.0123 it work but if i try 1.123 it don't wok, if i try 0.1 is don't worki have try this...
2 Feb 2012 by Wendelius
Do you mean that you must have at least two decimals. Perhaps something like:\d{1}.(\d){2,32}
2 Feb 2012 by Rajeev Jayaram
Check this similar post,SOF[^]Hope it helps.
7 Oct 2010 by Mahendra Kumar Srivastava
Gives splitted values taking csv string as input.
18 Aug 2011 by Herre Kuijpers
A utility that allows you to enter simple and more complex mathematical formulas which will be evaluated and calculated on the spot
16 Aug 2013 by hsakarp
Hi, I am using the REgEx "^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+[.])*(\.[a-zA-Z]{2,17})$"to validate Email but with that i am trying to resolve the MS Email Format.It satisfies all the format but i cant validate the below mentione format.Valid:...
16 Aug 2013 by Thomas ktg
Hi hsakarp,http://regexlib.com/RETester.aspx?regexp_id=90[^]You can use the above link to test your Regular Expression by changing it for your own needs.You can easily find the solution by changing the regex.
16 Aug 2013 by Dholakiya Ankit
Valid: david.jones@proseware.comValid: d.j@server1.proseware.comValid: jones@ms1.proseware.comInvalid: j.@server1.proseware.comInvalid: j@proseware.com9Valid: js#internal@proseware.comInvalid: j..s@proseware.comInvalid: js*@proseware.comInvalid: js@proseware..comInvalid:...
19 Aug 2013 by hsakarp
here is the code which will compare both the formats.UNfortunately i am using two loops to check the valid Email Addressif (Input.match(/^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\_[a-zA-Z0-9-]+)*(\#[a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+[.])*(\.[a-zA-Z]{2,17})*(\.[a-zA-Z]{2,17})$/)) { ...
29 Jun 2013 by Ghosuwa Wogomon
An example of a clean way to implement classes in C
7 May 2010 by Chris Trelawny-Ross
I agree it would be nice to be able to use the group name in the switch; unfortunately the Group object doesn't have a Name property (and neither does its base class Capture) so the best you'll be able to do is the following:string ReplaceMatch(Match m) { if...
3 May 2010 by OriginalGriff
I am using a Regex with a MatchEvaluator delegate to process a format string, e.g. "Time: %t, bytes: %b" would replace the "%t" with a time stamp, and the "%b" with a bytes count. Needless to say, there are loads of other options!To do this, I use: Regex regex = new...
15 Sep 2011 by valza
Hi, I am trying to make Regex pattern.so, the user input string with letters. ("bcade") what is the Regex pattern, to make this input look like -> abcde? Thanks for answers :)
15 Sep 2011 by OriginalGriff
There is no sensible regex which will do that - it is a job for a sort routine.The easiest way is to convert the string to a character array, sort it, and convert back to a string again.string s = "bcade";char[] chars = s.ToCharArray();Array.Sort(chars);s = new...
2 Jan 2015 by smksamy
in this coding I replace all roman letter terms to SMALLCAPS,CAPS CASE, LOWER CASE , the ALLCAPS value cant convert to other cases public void OxidationNumbers(string scase) { if (_doc == null) return; else if...
6 Jan 2022 by honey the codewitch
This article describes an improvement to the state removal algorithm for converting FAs to regular expressions
15 Nov 2012 by kurtiniadiss
Hi all,I want to use a regular expression statement in my asp.net 1.1 project to validate float numbers which can have ", . " as floating seperators. I am new in this topic, please help me.Thanks in advance.
15 Nov 2012 by OriginalGriff
5 Jan 2011 by Bryian Tan
ASP.NET Password Strength Regular Expression. Customize n numbers of upper case, digits, special characters.
23 Jun 2011 by Phan7om
Hi AllI am using ASP.Net's RegularExpressionValidator to validate email addresses. But this is not working in IEv6 and IEv7.After research although I found the culprit is lookahead and lookbehind but was unsuccessful in removing them from the regex and get a general regex that runs in all...
23 Jun 2011 by OriginalGriff
Get a copy of Expresso [^] - it's free, and it examines and generates Regular expressions.It also has sample expressions: It's one for emails is:([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})
23 Jun 2011 by Phan7om
After not finding a regex without lookaround, I used server side validation
17 Oct 2014 by Nikolaj jensen
How do i meet this criteria:MatchAAA123.xlsxBBB123.xlsxDon't Match~$AAA123.xlsxThe below seems to work, but how can i check for the ~ ?[^\$](AAA|BBB)123.*.xlsx
17 Oct 2014 by OriginalGriff
Use the start-of-string and end-of-string indicators:^(AAA|BBB)123.*\.xlsx$Note the backslash before the final dot '.' character - if you don't have that then it matches any character, so it would match AAA123myxslx.txt as well.Get a copy of Expresso [^] - it's free, and it examines and...
21 Oct 2014 by Nikolaj jensen
Thanks for your help!I tried the Expresso tool - nice.however i see some strange issues..--------------------------------------------------------------[^\$](AAA|BBB)123.*.xlsx Is working in my C# program Match AAA123.xlsx BBB123.xlsx Don't Match ~$AAA123.xlsxBut...
16 Dec 2022 by Arifin Mustafa
>"123-456-7890".match(/(\d{3})...
16 Dec 2022 by Richard Deeming
It's not at all clear what you're trying to do, but your input clearly doesn't match the second pattern. Your first pattern matches any three digits, followed by a "-", followed by any other three digits. Your second patter matches any three...
1 Mar 2018 by Medtronic WPF Developer
Hello I believe that there is a better way to use RegEx in C# than I have done below: public override object ProvideValue(IServiceProvider serviceProvider) { Regex r = new Regex("{.+}"); var matches = r.Matches(String); var replacer = new...
1 Mar 2018 by Richard Deeming
Something like this should work: private static readonly Regex Pattern = new Regex("{(.+?)}", RegexOptions.Compiled); public override object ProvideValue(IServiceProvider serviceProvider) { return Pattern.Replace(String, match => { string newMatch = match.Groups[1].Value; ...
19 Oct 2011 by 01.mandar
i have written Bluetooth code in win32 which detected bluetooth devices in range andafter installing bluetooth device on my PC it creates more than one COM portto get serial port i search in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSetbut some time the newly installed bluetooth do not...
19 Oct 2011 by André Kraak
Have a look at the answer[^] to a similar question[^] here on CP.
19 Apr 2011 by amit_upadhyay
Iam having a trouble implementing a certain technique - selecting next text in a richtextbox control which is underlined.You see iam trying to make a word processor but am stuck. I have been able to write the code to select each word one-by-one on pressing F1. Now i want to select only those...
19 Apr 2011 by OriginalGriff
Run myRichTextBox.Rtf through this:// using System.Text.RegularExpressions;public static Regex regex = new Regex("(?
29 Sep 2021 by Member 15375454
Hi, how I can build a Regex that will bring me as first Group Mustermann filiale01 and second Group "M" from Max after Comma. This are my fields: Mustermann, Max filiale01 My result should be: MustermannM filiale01 My goal ist to...
29 Sep 2021 by OriginalGriff
Try this: (\w+(?:,\s+)\w{1})(?:.*?^^)(.*) You will probably need MultiLine and SingleLine Regex options set.
30 Jun 2013 by sajid zafar_Iqbal
i am developing a web application where i meet some custom requirements , that the text boxes would only accept a to z and 0 to 9 and also allow these cahr& " ; , . - # @ / {}these characters and deny all other inputs...how to make this regular expression ???
1 Jul 2013 by sjelen
var r = new System.Text.RegularExpressions.Regex("^[a-z0-9&\";,.\\-#@/{}]*$");
9 Sep 2011 by sumair_coolboy
want to remove first and last character of any word by using regex....FOr example..(HELLO) (WORLD) will return === HELLO WORLDand (HE/LLO) (WO/RLD) will return ====== HE/LLO WO/RLD or //Hello WOrld/ will return ========= Hello WOrldor (HELLO) (W/ORLD) STACKOVERFLOW) will...
9 Sep 2011 by #realJSOP
Why use regex? // I would personally make this an extension methodpublic static string ReplaceOccurrence(this string str, string target, string replacement, int count){ int pos = -1; int counted = 0; string result = ""; do { pos = (pos >= 0) ?...
15 Oct 2012 by sachinDabas
Hi All, I have a scenario where i need to replace tag with tagInitial Code some text more text-----------------Code implemented--------------------------------------------------- replaced with replaced with...
15 Oct 2012 by Anandkumar D
You need to handle it (style with div) separately........data.Replace("", "").Replace("", String.Empty).Replace("", "").ToString();
15 Oct 2012 by n.podbielski
So maybe you will parse this data as XML.http://msdn.microsoft.com/en-us/library/cc189056%28v=vs.95%29.aspxThis way you will not have to change it everytime data will change.I am not sure if xml parser will be sufficient for this. I should if your data will be simple enough and...
16 Oct 2012 by Michel [mjbohn]
using System.Text.RegularExpressions;[...]private string ReplaceDivTagToBrakeTag(string data){ Regex regEx = new Regex(@"(.*)"); Match m = regEx.Match(data); return "" + m.Groups[1].Value.Trim();}
20 Feb 2013 by niko_tells
hi,i cant find a regex pattern for unallowed signs ( ? " : | \ / * ) in a dataname, could anybody give me this pattern please?thank you
20 Feb 2013 by Joezer BH
Try this:string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));Cheers, Edo
24 Apr 2023 by Evilfish2000
I am reading the headers of an email message where the headers look like this: Date: 24 Apr 2023 09:43:44 +0200 Subject: HELP! Location 'Name249fc8e9-068b-47c3-a39c-a3e4cdfe2c16' is not responding! Content-Type: text/plain; charset=us-ascii...
24 Apr 2023 by Richard Deeming
As discussed in the comments, Microsoft officially recommend using MimeKit[^] for all email-related code. It's free and open-source, and it's actively maintained: GitHub - jstedfast/MimeKit: A .NET MIME creation and parser library with support...
13 Nov 2010 by He11iK
Can not get why my Regex class can not instantiate. The regular expression seems to be fine, but i'm getting error message when calling "BuildStructure":System.ArgumentException : parsing "[(.*?;)(([(if)(while)(for)]).*?\(.*?\){({.*?})*?})]" - Too many )'s.Here is the code:class...
14 Nov 2010 by OriginalGriff
You either have an extra backslash: "[(.*?;)([(if)(while)(for)]\s*?\(.*?\){({.*?})*?})]"becomes"[(.*?;)([(if)(while)(for)]\s*?(.*?\){({.*?})*?})]"or one too few:"[(.*?;)([(if)(while)(for)]\s*?\(.*?\){({.*?}\)*?})]"
22 Dec 2011 by pavel.bidenko
Hi everybody, I got a problem with regex, hope someone can help me.I have a list of strings and each string contains uppercase word of 17 letters, I need to get this word from string.Something like this: string pattern = @"[A-Z0-9]{17}"; Regex regex = new Regex(pattern); ...
22 Dec 2011 by Monjurul Habib
Try following:C# Regex.Split Method Examples[Updated]If you are looking for more advanced Regular Expression, follow the below links:Regular Expressions Cheat SheetLearn Regular Expression (Regex) syntax with C# and .NET
22 Dec 2011 by Drazen Pupovac
I tried and its works: List list = new List(); list.Add("ASD"); list.Add("ASFsdsd"); list.Add("adsASFsdsd"); string pattern = @"[A-Z]{3}"; Regex regex = new Regex(pattern); List result = new List(); foreach (string val in...
6 Jun 2011 by mylogics
Can any body tell me how I can validate a textbox control dynamicaally. There should only be 10 digits in the textbox. For this I have coded it as:RegularExpressionValidator expvalidator = new RegularExpressionValidator(); TextBox txt = new TextBox(); ...
6 Jun 2011 by Prerak Patel
1. You can use \d{10} instead of @"\d\d\d\d\d\d\d\d\d\d"2. What is this : expvalidator.IsValid.IsValid?Edit ----Because the default value of this property is true, it will return true if you query this property before validation is performed. For example, this might occur if you attempt...
6 Jun 2011 by naraayanan
Hi, try thisTxt.Maxlength =10;Regards,Lakshmi Narayanan.S
6 Jun 2011 by mylogics
finally got the solution like this:if (System.Text.RegularExpressions.Regex.IsMatch(txtComplainantContact.Text, @"\d\d\d\d\d\d\d\d\d\d")) { } else { Page.RegisterStartupScript("javascript", "alert('Please Enter10...
17 Jan 2013 by Sebastian T Xavier
Hi everyone,Can someone help me write a C# regular expression to extract "2.224 KB" from the following string @{AnyText=2.224 KB (2,277 bytes)RegardsSebastian
17 Jan 2013 by dan!sh
More information is required before this can be answered appropriately.Assumptions:1. String always remains like: "@{AnyText= (2,277 bytes)"2. This is the total string and not a part of a huge string.You can get substring from the string provided.1. Get the index of...
20 Jan 2013 by Andreas Gieriet
How about:...string input = ...;Match match = Regex.Match(input, @"\w+\s*=\s*(\d+(?:\.\d+)?\s*[A-Z]+)");string size = match.Success ? match.Groups[1].Value : string.Empty;...Depends very much on the input string if the @ and { are relevant to properly match the text.Note: If you...
21 Jul 2014 by Carl Mailey
Hi guys, I'm hoping someone wouldn't mind writing me a complex regular expression, preferably in c# for splitting html text. basically looking for an array that contains all the formatting tags as strings in the array and also every separate word. Maintaining the order of the words is...
21 Jul 2014 by OriginalGriff
Don't do it - it's pretty horrible, and far, far too easy to break. And far, far to complicated to fix! :laugh:Look at parsing it properly instead - there are some good ones out there, but this one will get you started: Parsing HTML Tags in C#[^]Or this: Another C# Legacy HTML Parser Using...
26 Jul 2010 by xJorDyx
This is one of my regular expressions:(?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?),(?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)The input would be 2 floats separated by a comma2.34,-23It creates 2 main groups "RollP" and "RollI" and i want to be able to take the...
26 Jul 2010 by Toli Cuturicu
Try indexing the Groups by Name:myMatch.Groups["RollP"]and so on.
10 Apr 2011 by Member 7762422
Hi,I need to filter everything before the backslash. For example domain\username, domain and the backslash must be filtered and removed.I tried this but it aint working.var x = IPGlobalProperties.GetIPGlobalProperties().DomainName.ToUpper();string s = Regex.Replace(x,...
10 Apr 2011 by anvas kuttan
Find a character is present in string or not string abc = "anvas the real napster /"; char[] SpecialChars = "*-_= /".ToCharArray(); int indexOf = abc.IndexOfAny(SpecialChars); if (indexOf != -1) { //there should a...
10 Apr 2011 by Pratik Bhesaniya
Hi,Try this,char[] separator = new char[] { '\\' }; string[] new_x= x.Split(separator,3);It will split ur String ( i.e x)into 3 parts i.e new_x[0],new_x[1],new_x[2].check which string of array contains ur answer and just use it.I think in ur case new_x[1] will hold...
10 Apr 2011 by Ashishmau
u can do like this alsostring s = "domain\\username"; string a = s.Substring(s.IndexOf("\\")+1);Hope it helps
10 Apr 2011 by Michel [mjbohn]
If you want to remove all characters from beginning of the line upto the first "/" in front of the part you want to keep (and including "/") this is your regex: Regex.Replace(x, @"^.*\/(.*$)","$1");