Posts

Showing posts with the label Regular Expression

Donate

How To Extract The Node Name In The Self-Closing Tags Using Regular Expressions In C#

Image
Hello, In one of the parser that I made, I need to extract the node name which is in a self closing XML tag as part of the requirement for the output. In order to do that, you need to combine a positive lookbehind for the lesser than symbol (?<=<) and positive lookahead for the forward slash and greater than symbol (?=/>). And then perform a greedy search in between those groups. The complete pattern for that is presented on the code snippet below. var NodeValue = Regex.Match(lstTempNodes[i], @"(?<=<)(.*)(?=/>)" ).Value.Trim(); Here's the pattern matching of several self-closing XML tags. Source Code: How To Extract The Node Name In The Self-Closing Tags Using Regular Expressions In C#

How To Calculate Due Days Excluding Weekends In C#.NET

Here's a function that will calculate the number of days excluding weekends. The parameters passed are the priority which contains number of days and the current date. Sample priorities are 'High[1 day]', 'Average [2 days]' and 'Low [5 days]'. The function then uses Regex to extract the whole numbers from the priority string to be used for incrementing the number of days. public DateTime RecalculateDueDate( string priority, DateTime Today) { int days; int count; DateTime dueDate; count = 0; dueDate = Today; days = int .Parse(Regex.Replace(priority, "[^0-9]" , "" )); while (count < days) { dueDate = dueDate.AddDays(1); if (( int )dueDate.DayOfWeek != 0 && ( int )dueDate.DayOfWeek != 6) count++; } return dueDate; } Source Code: How To Calculate Due Days Excluding Weekends In C#.NET

Data Annotation Validation Of TimeSpan Property In Model Using RegularExpression Attribute

Hello, To validate a model property of type TimeSpan using Data Annotation RegularExpression attribute, the expressions should check the hours, minutes and seconds since the corresponding database column in SQL Server that is mapped with this field has a Time data type. The example below validates a 23 hour format military time and does not allow minutes or seconds greater than zero. [RegularExpression(@"^(?:[01][0-9]|2[0-3]):[0-0][0-0]:[0-0][0-0]$ ", ErrorMessage =" Invalid time format and hh:mm:ss values. ")]

Bootstrap Table JavaScript Data-Sorter For Currency Column

Image
If your Bootstrap Table by Wenzhixin has a string currency column with a dollar sign and you want to sort the amount which disregards the currency symbol, a solution would be to remove the currency symbol and comma using Regex in JavaScript. function AmountSorter(a, b) { var billA = Number (a.replace( /(^\$|,)/g , '' )); var billB = Number (b.replace( /(^\$|,)/g , '' )); if (billA < billB) return - 1 ; if (billA > billB) return 1 ; return - 0 ; } And in your Bootstrap Table column, set the data-sorter property with the name of your currency sorter function. <th data-field= "RegistrationFee" data-sortable= "true" data-sorter= "AmountSorter" > Registration Fee </th> Output Sample Fiddle: Bootstrap Table JavaScript Data-Sorter For Currency Column

Match Item That Exists In A List Using Regular Expression And LINQ

Hi! Using Any() in LINQ, we can match/find an item that exists in a List<T> or IEnumerable using Regular Expressions. if (Products.Any(t => Regex.IsMatch(t, ProductsFromFrance.FrenchProdPattern)) { //true statement here.. } Where Products is the List object and ProductsFromFrance.FrenchProdPattern is the Regular Expression pattern.

Match Network Path In A String Using Regular Expression

Hello, While working on a project, I was confronted with an issue on how to match or extract a network path. Normally, you can use string functions or built-in .NET code to check the validity of a path, but since I'm also refreshing my skills in Regular Expression. I prefer the latter as the solution. So the pattern to match the server path is presented below: ((\\\\)?((?<Folder>[a-zA-Z0-9- _]+)(\\.*[a-zA-Z0-9-_ \\])(?="))) And to declare that pattern in your C# code, you have to escape the back slash characters. string ServerPath = "((\\\\\\\\)?((?<Folder>[a-zA-Z0-9- _]+)(\\\\.*[a-zA-Z0-9-_ \\\\])(?=\")))" ; The input strings tested are as follows. Const ImagesPath As String = "\\ImagesServer\Logo Files\InetPub\TempProjects\" Const docsPath As String = "\\docsPathServer15\Health\Physicians\" Const vsPath As String = "\\vsServer909\vs2017\Projects" string manual = "\\manualServer\CompanyRules\EmployeeFiles\Cebu&

Regular Expression Extract Url From String Using Regex.Matches() In C#

Here's how to extract url(s) from a string or document using Regex.Matches() method. The Regex.Matches() method returns an array object MatchCollection in which you can access individual elements using it's index. Code: 1 2 3 4 5 6 7 8 9 10 11 12 string pattern = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?" ; string Input = "<<abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\"abcd\" href=\"https://mediatemple.net\"" + "Sample text for testing>http://regexr.com/foo.html?q=bar>" ; string url1 = string .Empty; string url2 = string .Empty; if (Regex.Matches(Input, pattern).Count > 0) { MatchCollection matches = Regex.Matches(Input, pattern); url1 = matches[0].Value; url2 = matches[1].Value; }

Split A String With Multiple Space As Delimiter Or Separator Using Regular Expression Or String.Split In C# and VB.NET

Given that you have a string that you want to split and the separator is two or more spaces. You can achieve using split() or Regex. VB.NET 1 2 3 4 5 6 7 8 Dim str As String = "Rule Name: WhosThere-176.44.28.203" Dim whosThereVar As String Dim whosThereString As String 'using split whosThereVar = str.Split( New String () { " " }, StringSplitOptions.RemoveEmptyEntries)( 1 ).Trim() 'using regex whosThereString = System.Text.RegularExpressions.Regex.Split(str, "\s{2,}" )( 1 ) C# 1 2 3 4 5 string str = "Rule Name: WhosThere-176.44.28.203" ; //using split string whosThereVar = str.Split( new string [] { " " }, StringSplitOptions.RemoveEmptyEntries)[ 1 ].Trim(); //using regex string whosThereString = System.Text.RegularExpressions.Regex.Split(str, @"\s{2,}" )[ 1 ];

Using PATINDEX() In SQL Server As An Alternative To Embedd Regular Expressions In SQL

Image
This was based on a post from SQL Team on how to grab a 5 digit number from the string field which could utilize a regular expression like this: [0-9 ]{5}. The initial solution was given by a forum member named Kristen. It could extract the 5 digit mark on a string field as shown below: DECLARE @strTest varchar(8000) SELECT @strTest = '\\servername\foldername99999\filename.ext' SELECT [ Position ]=PATINDEX( '%[0-9][0-9][0-9][0-9][0-9]%' , @strTest), [ Before ]= SUBSTRING (@strTest, 1, PATINDEX( '%[0-9][0-9][0-9][0-9][0-9]%' , @strTest)-1), [ After ]= SUBSTRING (@strTest, PATINDEX( '%[0-9][0-9][0-9][0-9][0-9]%' , @strTest), LEN(@strTest)) What if the string field would contain two or more 5 digit information, how can you achieve that? The answer is to include while loop in TSQL and some additional string functions to achieve the desired output. Here's a sample stored procedure: USE TESTDB; GO CREATE PROCEDUR

Remove HTML Tags In An XML String Document Using Regular Expressions (REGEX) In C#

Here's a regex pattern that will match html tags that are present in an xml string document. Where xml, node1, node2, node3, node4, node5, node6 and node7 are xml tags. node1 could represent a valid xml tag name like employername or similar tag names. xmlStringData = Regex.Replace(xmlStringData, @"<((\??)|(/?)|(!))\s?\b(?! (\b(xml|node1||node2|node3|node4|node5|node6|node7)\b))\b[^>]*((/?))>" , " " , RegexOptions.IgnoreCase); Greg

Regular Expression Remove Day Name And Date Suffix In C#

In a situation where i want to format this date value from (Tuesday 19th March 2013) to (19 March 2013). I made a regular expression by applying look behind approach and ends with behavior in strings. Here's the expression: indicatorDate = Regex.Replace(indicatorDate, @"(\b[A-Za-z]*day\b)|((?<=[0-9])[a-zA-z]{2})" , string .Empty, RegexOptions.IgnoreCase); :)

The Controller For favicon.ico Does Not Implement IController

In an application using Controller factory, i encountered an error as stated in the title. My MVC does not have a favicon.ico. The solution is to add a parameter constraint that does not allow .ico filenames in your routes. I got the solution from forums.asp.net routes.MapRoute( "Default" , // Route name "{controller}/{action}/{id}" , // URL with parameters new { controller = "ProductView" , action = "Index" , id = "" }, // Parameter defaults new { controller = @"[^\.]*" } // Parameter constraints (regex/string expression) );

Regular Expression Match Capture Index Property Returns 0 Instead Of -1 In C#

Yesterday, while working on Regex Index property, I encountered a weird problem. Supposedly, string.indexOf(string variable) returns -1 value if there's no occurrence of such substring. However, using Regex.Match(source.ToLower(), @"regex pattern" ).Index returns 0 if instead of -1 if no such substring occurs. The solution was pointed out in stack overflow: Return index position of string after match found using Group.Success in which case returns a boolean value. So, here's the tip: if ((Regex.Matches(source.ToLower(), @"<ol[^>]*>" ).Count < 1) && (Regex.Matches(source.ToLower(), @"<ul[^>]*>" ).Count > 0)) { if (Regex.Match(source.ToLower(), @"<ul[^>]*>" , RegexOptions.IgnoreCase).Success) { // your if statements here.... :) } } Greg

Regular Expression Word Boundary Not Working If Using A Variable In C#

In this scenario, I have to match an exact state abbreviation (QLD) that is Queensland. I declared an array containing state constant values. Normally this would work without using a string variable in C#: Regex.IsMatch(address, @"\bQLD\b" ) However, this won't work: if (Regex.IsMatch(address, @"\b" + str + "\b" )) The solution is to put an @ sign on both "\b" of the expression: string [] states = new string []{ "ACT" , "NSW" , "QLD" }; foreach ( string str in states) { if (Regex.IsMatch(address, @"\b" + str + @"\b" )) { state= str; address = address.Replace(str, "" ).Trim(); break ; } }

Regular Expression In html List Tag Not Working In Multiline String In C#

I have this string: < li class="MsoNormal" style="color:white;mso-themecolor:background1; mso-margin-top-alt:mso-list:l1 level1 lfo1;tab-stops:list 36.0pt"> and the regex has a lazy quantifier to replace the string above to < li>. Using a simple regex pattern, it won't change the string above to ordinary < li>. The solution would be to add a regex to replace new line characters. Since the string has newline characters. Regex.Replace(source, @"\n" , string .Empty, RegexOptions.IgnoreCase);

Remove Open And Close Square Brackets In A Sentence Using Regular Expression In C#

Given the sample string data [Posted Friday September 23 2011] and you need format the sentence like this Posted Friday September 23 2011 without the square brackets, a solution would be to use Regex. string date = Regex.Replace(date, "[\\[\\]]" , string .Empty); date = Regex.Replace(date, @"[\[\]]" , string .Empty);

Regular Expression Remove String With A Punctuation Beside It In A Sentence In C#

Assuming in a sentence, you want to remove the word apply now in any case. This word has a punctuation beside it. Example: Apply now! Apply now. APPLY NOW! APPLY NOW. apply Now! apply Now. In a sentence: We are in need of VB.NET Developers. Apply Now! We are in need of VB.NET Developers. Apply now! We are in need of VB.NET Developers. APPLY NOW! We are in need of VB.NET Developers. apply now! To remove, just use the code below: description = Regex.Replace(description, "apply now[!.]" , string .Empty,RegexOptions.IgnoreCase).Trim(); Note: I'm not a Regex expert.

Formatting Numbers With Comma Using Regular Expression In JavaScript

In asp.net c#, this can be achieved by String.Format(), however in javascript/jquery, this can be achieved using a simple JavaScript function: 1 2 3 4 5 6 7 8 9 10 11 function addCommas(nStr) { nStr += '' ; x = nStr.split( '.' ); x1 = x[ 0 ]; x2 = x.length > 1 ? '.' + x[ 1 ] : '' ; var rgx = /(\d+)(\d{3})/ ; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2' ); } return x1 + x2; } In your script, you can call it using: 1 2 3 var number = 123456.99 ; var result = addCommas(number); alert(result); Source: JavaScript Number Format

Donate