Click here to Skip to main content
15,885,278 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 Score

Regular Expressions 

31 Oct 2014 by Christoph Buenger
Describes PHP application development with the free Scavix Web Development Framework (Scavix-WDF).
21 Nov 2019 by honey the codewitch
Build a feature rich, non-backtracking regular expression engine and code generator in C#
10 Nov 2021 by honey the codewitch
Embed fast streaming C# code to match text based on inputted regular expressions
23 Nov 2009 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.
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...
31 Mar 2019 by honey the codewitch
A Non-Backtracking Regular Expression Engine for .NET (Core)
2 Jan 2024 by honey the codewitch
This article presents a program to help visualize regular expression mechanics.
2 Jan 2021 by honey the codewitch
Hoodwink your computer into doing your work for you using regular expressions
15 Nov 2023 by honey the codewitch
Generate tight C code to match text based on regular expressions
27 Sep 2019 by Mohamed Kalmoua
In this article, I will discuss a WiFi password recovery and management tool that I created in WPF using Visual Studio 2019.
15 Jun 2012 by VJ Reddy
I think the matching with prefix and suffix options of Regex can be used to extract only the required value from the parentheses as shown below:string text = @"STRING[261] Directory(\FTP\OSP_003\)\nSTRING[9] FileName(SysParaI)\nSTRING[4] FileExtension(002)";Match match = Regex.Match(text,...
15 Jan 2024 by honey the codewitch
In this article, we will use my Visual FA solution to explore finite automata concepts used for finding patterns in text.
18 Oct 2011 by George Swan
The Regex method uses comma, full stop, hyphen, and apostrophe as word separators. The problem with this is that these characters are not universally used as separators. The hyphen is used to join two words. Could I suggest the following?string input = "Mr O'Brien-Smith arrived at 8.30 and...
5 Jan 2011 by Bryian Tan
ASP.NET Password Strength Regular Expression. Customize n numbers of upper case, digits, special characters.
3 Feb 2020 by honey the codewitch
A Pike virtual machine and optimizing compiler for regular expressions using an NFA engine
20 Jan 2011 by Rob Philpott
OK - this is a bit of algorithmic fun and I'll tell you how I'd go about it, but you'll have to figure the code out yourself.You need to combine a forward reading parser with a recursive object or functional call. On every open tag you need to go one level further of recursion, storing the...
23 Apr 2015 by CHill60
Essentially you are attempting to parse the grammar in the string.See this CP article Parsing Expression Grammar Support for C# 3.0 Part 1 - PEG Lib and Parser Generator[^] which is also referenced from this post[^] that includes some alternative ideas.Here's an academic paper[^] on the...
2 May 2016 by George Jonsson
You can try thishttp:(?:(?!http:).)*It will match from http: up to the next occurence, but not including it.The result of your sample string will be 3 separate matches.[UPDATE]Forgot the https variant:http(?:s)?:(?:(?!http(?:s)?:).)*
14 Jul 2019 by honey the codewitch
Creating a simple parser in 3 easy lessons
1 Feb 2020 by honey the codewitch
Add non-backtracking fast DFA regular expression and finite state automata to your projects
25 Dec 2021 by honey the codewitch
Explore, run, and manipulate DFA regular expressions from graphs, to state machines with this library
19 Dec 2010 by PIEBALDconsult
How about loading it into an XmlDocument and getting the InnerText? (Provided the HTML is well-formed XML, of course.)
20 Dec 2010 by JHoye
Consider using the open source HTML Agility Pack library (htmlagilitypack.codeplex.com).It lets you use XPATH queries to access very specific parts of an HMTL document, and the HTML does not have to be valid, well-formed XML. In addition to accessing the raw inner text of an element you can...
23 Dec 2010 by OriginalGriff
Try([a-zA-z]...
14 Apr 2012 by VJ Reddy
One option is to split the original string at the location of ? and reconstruct using @param as shown belowSub Main Dim statement As String = "INSERT INTO X (a,b,c) values (?,?,?)" Dim statements As String() = statement.Split("?"C) 'Construct a stringbuilder Dim sb As New...
15 Jun 2012 by Clifford Nelson
You can go simple and justRegex r = new Regex(@"\(.*\)");var e = r.Matches(s);e is a collection of matches, and will include the "()"Will not requerRegex r = new Regex(@"\((.*)\)");var e = r.Match(s);e.Groups will contain all matches, the second item will your result
6 Sep 2012 by Volynsky Alex
Regular expression, or often known as regex, is a pattern that consist of rules used to match a certain set of strings. They are extremely powerful, and you’ll need them in most programming languages you come across, especially when there’s a need to scan and match context for further...
6 Sep 2014 by Marco Bertschi
A walk-through on how a Key-Value pair can be parsed using a PERL-compatible regex engine
19 Apr 2014 by Peter Leow
Try this:^[a-zA-Z]+(\s[a-zA-Z]+)?$
5 Jan 2015 by DamithSL
sample code:var splitwords =new string[] {"egg","eggs", "have a receipt"}; string input ="I have a receipt with eggs but others with just one egg";foreach (string word in splitwords){ var regex = new Regex(@"(?
15 Mar 2016 by Jochen Arndt
It is returning a length of 350 because the string contains 350 characters.To verify this, select the text and paste it into an Unicode editor (e.g. with Notepad++ choose File - New, Encoding - UCS-2 Little Endian, and paste the text). Within Notepad++, it will look like (shortened, there...
22 Jul 2020 by siliconvideo
This StringBox control implements keystroke validation using regular expressions and a touch of glue logic
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*?\(.*?\){({.*?}\)*?})]"
11 Jan 2011 by #realJSOP
It's certainly the fastest way to type it.If you want to try to find faster ways, be a programmer and try different ways to approach the problem.Performance for such a task would greatly depend on the length of the string involved.
30 Mar 2011 by OriginalGriff
Unfortunately, AFAIK there is no way top make a regex which replaces "one of these" with "one of those".You can clean it up a bit, by using a MatchEvaluator to remove the need for a String builder. Make the regex just a list of known invalid characters and: result =...
26 May 2011 by Kim Togo
Try this Regex: ,(?!(?
20 Nov 2011 by Michel [mjbohn]
This is a so called 'regular expression' (RegEx).Just have a look at this :http://en.wikipedia.org/wiki/Regular_expression[^]Your RegEx will match when:0 or more whitespaces (\s*)are followed byexactly two digits (\d{2})followed by ':'followed by 0 or more whitespaces...
22 Feb 2012 by Peter_in_2780
The first thing to do is to write down exactly what you want to match. From your examples, it looks to me like this is a good start:a non-letterfaceoptional apostropheoptional sa non-letterTranslated into a regex, this turns into[^a-zA-Z]face\'?s?[^a-zA-Z]You then need to...
11 Apr 2012 by Mehdi Gholam
Use :(?\(\s*\?.*)+Which will give you the (...) portion and then just count the number of ? chars and replace with @paramN where N is an iterator.
16 Apr 2012 by Lutosław
Find patterns in a sequence of objects using a familiar language.
20 Jun 2012 by Tim Corey
Note: These suggestions aren't Regex specifically, which I know you asked for. I'll work on a RegEx for you as well, but these solutions seem simpler and lighter than full RegEx:Pass the file names into the GetExtension method like so:string extension =...
21 Jun 2012 by AspDotNetDev
You want a negative lookahead or a negative lookbehind. Suppose you want to validate so that a phrase starts with "string" and ends with "bee", but does not contain "like". You could use this regular expression (which uses a negative lookahead):(?!.*like)^sting.*bee$The negative look ahead...
12 Sep 2012 by Clifford Nelson
Look at the following tip (do not consider it an article, although so classified): Converting Wildcards to Regexes[^]
27 Sep 2012 by Yvan Rodrigues
Replace ntext\(\d+\) with TEXTReplace DEFAULT\(\((\d+)\)\) with DEFAULT '$1'
25 Feb 2013 by Joezer BH
Hello Choudhary, \w in regex means: any word character (letter, number, underscore)you may use . (dot) that means: any single characterGood luck, Edo
10 May 2013 by André Kraak
I found a similar question on Stack Overflow[^] and used its answer on your problem.The idea is to split only on comma's that have an even number of or no single quotes after it.Using this expression I got the result without the additional blank line you are looking for....
30 Oct 2013 by strogg
Try this instead of enclosing your exp with [^\d]...regex...[^\d](?
16 Jun 2014 by Peter Leow
^[a-zA-Z][a-zA-Z\s\-]*$
8 Sep 2014 by cogi83
A SW to send your WAN IP and other info via email
1 Nov 2014 by George Jonsson
Basically you can replace the keyword @city with \s+(?[\S\s]+?)\s+Example:string template1 = @"^Tell me the forcast of\s+(?[\S\s]+?)\s+for\s+(?[\S\s]+)$";In C# you useMatch m = Regex.Match("Tell me the forcast of Las Vegas for tomorrow", template1);if...
10 Nov 2014 by PIEBALDconsult
I have been unable to determine what the meaning of \Q is in Java, but in Perl, it's:\Q quote (disable) pattern metacharacters until \E\E end either case modification or quoted section,This doesn't appear in the .net implementation and seems needless in your...
12 Dec 2014 by Unihedron
See this regex:/^(?=[^a]*a)(?=[^n]*n)(?=[^u]*u)/iRegex explanation:^ Asserts position at start of string.(?=[^a]*a) Asserts that "a" is present after all the non-"a"s.(?=[^n]*n) Asserts that "n" is present after all the non-"n"s.(?=[^u]*u Asserts that "u" is present after all...
12 Dec 2014 by Maciej Los
The same you can achieve using Linq[^] query:string[] words = new string[]{"Anitha", "Nandu","anushka","jayasree"};var qry = from w in words where w.ToLower().Contains('a') && w.ToLower().Contains('n') && w.ToLower().Contains('u') select w;foreach(string word in...
21 Jan 2015 by Peter Leow
Try this:^[\d\._\w]+$also read: The 30 Minute Regex Tutorial[^]
12 Feb 2015 by Richard Deeming
Two problems with your code:You've used Regex.Match instead of Regex.IsMatch;You've missed the @ prefix on the second "\b" string;I'd also be inclined to add a Regex.Escape around the word to find, in case it contains any special characters.var listTobeDeleted =...
10 Nov 2015 by OriginalGriff
Try:$\d{9}[A-Za-z]^
7 Dec 2015 by Peter Leow
Try this:(?)\d\.\d\.\d.\d(?=\)The keys lie in:(?
22 Dec 2015 by Richard Deeming
Your parameters are the wrong way round - the first parameter is the string to test, and the second parameter is the regular expression to use:Regex.IsMatch(myString, ".* My name is XYZ")To retrieve the details of the match, use the Match method[^], which returns a Match object[^]....
4 Mar 2016 by Richard Deeming
Your pattern currently consumes the leading and trailing commas, so every other value is skipped.You need to use zero-width positive lookahead/lookbehind assertions instead:Regular Expression Language - Quick Reference[^]Also, it would be better to use [^\,]* rather than .*?, since you...
2 May 2016 by Patrice T
See solution 1 for a working solution.This site can help to see if a regex is doing what you expect.Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]I guess you will have to read regex documentation to understand advanced usages.perlre - perldoc.perl.org[^]By...
1 Jun 2016 by OriginalGriff
String.Split isn't a Regex - it's just a basic string method that can't do anything too complex.Try:("[^"]*")|([^\s]+)as a regex - it should give you what you want as separate Group values.
27 Sep 2016 by OriginalGriff
It's not a valid regex for a telephone number: what it matches is literally a single numeric digit followed by the text "{5-15}" and nothing else.What they probably meant to say was:^[0-9]{5,15}$Which matches "any string of numeric digits between 5 and 15 characters long,...
11 Jun 2018 by Member 10481957
Chronological Expressions is a RegEx inspired Pattern Matching Library and Specification for query event logs
25 Sep 2019 by MadMyche
Using RegEx for Credit Cards is at best rudimentary; you are better off validating what you are actually working with Credit Card numbers themselves are generally at least 16 digits long; the primary exception being American Express which uses 15 digits. CVV numbers are 3 digits long for most;...
22 Sep 2020 by Maciej Los
[EDIT] If you would like optionally to get first occurance of 99,00... For lines: My super data plan 10gb mobile 99,00 1 jul - 31 jul 2020 99,00 My super data plan 10gb mobile 1 jul - 31 jul 2020 99,00 Try this: ...
8 Nov 2021 by honey the codewitch
Deep dive some advanced source generation in a real world application
27 Oct 2022 by RickZeeland
You can practice with an online tool like RegExr[^] To match all spaces, + and - symbols try: ([ +-])+ To negate the result, try: ([^ +-])+ [Edit] To match lines, try: ([ +-]*\n)+
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...
9 Sep 2010 by Om Prakash Pant
Please check the following modified code:Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress Dim allowedChars As String = "0123456789" If e.KeyChar ControlChars.Back Then If...
5 Jan 2011 by MarcoBot
NOTE: If you're really wanting plain text, then you should also be sure to decode the HTML entities (System.Web.HttpUtility.HtmlDecode()) on the resulting text, or you'll wind up with HTML/XML character entity text in your output, such as & and [ If you're going to immediately output the...
8 Feb 2011 by Bryian Tan
How to extract the text from a hyperlink and preserve other HTML tags
26 Feb 2011 by DaveAuld
In case you have never heard of it, this is an excellent site. Contains cheat sheet and testers. As well as a list of predefined expressions.regexlib[^]That is a suggestion, i will see if i can come up with a solution!Edit: See you posted your question on that site also :doh: I will...
26 Feb 2011 by OriginalGriff
I wouldn't use a regex: you could but it would be quite complex and difficult to maintain.Instead, I would sort the characters in my input string, and then check it.If two adjacent characters are the same, fail.If any character is not in the set 'B', 'L', 'R', 'T', failOtherwise, pass.
29 Apr 2011 by Manfred Rudolf Bihy
Save yourself the pain and use XPath expressions[^] to dissect your XML.Regular expression are really no good for parsing nested structures.Best Regards,-MRB
6 May 2011 by OriginalGriff
Try:public static Regex regex = new Regex("para.*tabs.*", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);Get a copy of Expresso[^] - it's free,...
30 May 2011 by yesotaso
//Get related text blockstring subContent = Regex.Match(content,@"(?
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...
14 Jun 2011 by OriginalGriff
And I think you will continue looking: that is not something I would want to do with a regex, particularly since you do not know the length of the sequence to be checked for.Instead - since I assume this is for checking password strength - why not use existing code: Password Advisor[^] has...
1 Jul 2011 by Nyarlatotep
Hello, I cannot find a valid regular expression pattern for my needs.I have a sample string like this:I have four child of seven years each, [seven] years ago I had no child, because I was fourteennow, I want match and then substitute the words "four" and "[seven]".So I have...
7 Jul 2011 by OriginalGriff
Try:public static Regex regex = new Regex( @"^\(_\d*\)\s*", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled );string result =...
18 Aug 2011 by OriginalGriff
That actually quite difficult, and probably not suited for a regex at all. The problem is that you want to accept the "Peter" from "Peter's" but discard "5th". What you really want to do is probably use a dictionary (a proper one, rather than an .NET Dictionary class) and check for actual words....
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[^]
17 Oct 2011 by NewPast
Dim pattern="http.*\.flv"Dim pattern2="^http.*\.flv$"'^ means at the 1st of the line; $ means at the end of the line
25 Oct 2011 by Jacobs76
I also use a Regex expression to count words, which returns the same number of words as MS Word. I wrap the Regular Expression in a String extension method to make it easy to use.public static class StringExtensions{ /// /// WordCounts Regular Expression /// ...
6 Nov 2011 by RaisKazi
Have a look at below Articles.Learn Regular Expressions (RegEx) with EaseThe 30 Minute Regex Tutorial
20 Nov 2011 by RaisKazi
Have a look at below CodeProject Articles on "Regular Expressions".The 30 Minute Regex TutorialLearn Regular Expressions (RegEx) with Ease
13 Jan 2012 by OriginalGriff
In this case, try:ClosedAccountFile_(\d+)_(\d+)_(\d+)_(\d+).txtThis matches your example, and separates each of the numeric values out into it's own group within the match.You have top realize that Regexes are much, much more complex than SQL LIKE statements - the simplest form of "%" in a...
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 OriginalGriff
Try:Regex regex = new Regex("[a-zA-Z]");string result = regex.Replace(InputText,"#");Get a copy of Expresso [^] - it's free, and it examines and generates Regular expressions.
6 Feb 2012 by Andreas Gieriet
If you want to remove the whole select element with it's content, then you can do it with regex only if some constraints are met: no nested element of the same name (select in this case).Try this:string pattern = @"";CheersAndi
15 Feb 2012 by Andreas Gieriet
I think the following Regex and HtmlDecode would do:string html = ...;string textonly = HttpUtility.HtmlDecode( Regex.Replace(html, @"|", ""));Any HTML construct that would not be stripped off properly by this?
12 May 2012 by funboysclub
From Pins to Poops, your bookmark bar can do more. Read about the Skidmarklet... a JavaScript Bookmarklet and lessons in RegEx.
13 Jun 2012 by OriginalGriff
Try:^[1-9][0-9]{0,5}$
18 Jun 2012 by Prasad_Kulkarni
Try this:^(?=[0-9]{3,6}$)0*[1-9][0-9]{2,5}
18 Jun 2012 by OriginalGriff
This is a bit rough, because you don't describe it well:[1-9][0-9,]{0,5}Get a copy of Expresso [^] - it's free, and it examines and generates Regular expressions.
9 Jul 2012 by Manas Bhardwaj
I guess it should be like this:bool result1 = Regex.IsMatch("ABCDEF", @"^[A-Z]{2}$");bool result2 = Regex.IsMatch("ABCDEF", @"^[A-Z]{2,2}$");bool result3 = Regex.IsMatch("AB", @"^[A-Z]{,2}$");bool result4 = Regex.IsMatch("AB", @"^[A-Z]{2,2}$");If a caret (^) is at the beginning...
8 Sep 2012 by ridoy
http://www.java2s.com/Code/Java/Regular-Expressions/JavaRegularExpressionSplittext.htm[^]http://www.regular-expressions.info/java.html[^]http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation.shtml[^]http://forums.codeguru.com/showthread.php?292394-TIP-A-little-tutorial...
19 Sep 2012 by Aarti Meswania
if it is Windows Applicationset property of Textbox CharacterCasing = Lowerit will automatically convert uppercase letters to lowercase.string pattern="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$";and verify it when textbox's Leave event...