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

Hi I need some help refining my regEx

I need to split the example the numbers eg ". 2 " however I also need  to split on "--n. 5 " and keep the "n."
Note: i'm first splitting on ". 1 " has the preceding Lexical doesn't have '--'

What I'm getting is every number, which I don't need!
I do need the Lexical If there is 1 And the sentance

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        Regex SentanceSpit = new Regex(@"\.(\s+\d+\s+)|\.--([a-z]+\.)\s+\d+\s+");
        string Line = @"abandon v. 1 give up or over, yield, surrender, leave, cede, let go, deliver (up), turn over, relinquish: I can see no reason why we should abandon the house to thieves and vandals. 2 depart from, leave, desert, quit, go away from: The order was given to abandon ship. 3 desert, forsake, jilt, walk out on: He even abandoned his fianc,e. 4 give up, renounce; discontinue, forgo, drop, desist, abstain from: She abandoned cigarettes and whisky after the doctor's warning.--n. 5 recklessness, intemperance, wantonness, lack of restraint, unrestraint: He behaved with wild abandon after he received the inheritance.";
        // Output strings
		string Term;
		string Lexical; // not every example have diferant Lexical
        string[] WordsExample;
        string[] Words;
        string Example;
		string[] FirstSecond = Regex.Split(Line, @"\s1\s");
		if (FirstSecond.Length ==2)
		{
			string 

Open in new window

0
Starting with Angular 5
LVL 19
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Using MS SQL Server and regex matching, how do you handle optional (zero or one instances) of a character?

models
-----------
H55N6800UK
H55NU8700UK
H60NEC5600UK

SELECT model FROM models WHERE (model LIKE 'H[0-9][0-9]N[0-9][0-9][0-9][0-9]UK') OR (model LIKE 'H[0-9][0-9]NU[0-9][0-9][0-9][0-9]UK') OR (model LIKE 'H[0-9][0-9]NEC[0-9][0-9][0-9][0-9]UK')

The SELECT statement above returns the 3 rows but uses an OR with three different regex expressions.  What I would like to do is use a single regex expression where the U or EC in the 5th character position are optionally matched.
Ideally a single regex expression to handle this would be something like:
 'H[0-9][0-9]N Optional U OR Optional EC   [0-9][0-9][0-9][0-9]UK'

The matching needs to be relatively tight and just using the % wildcard would accidentally match more items in the database than desired.

In practice, I will have one table of models to match (tens of thousands of records) and a second table of model-related data that includes the regex match in one column.  Then I'll simply join the tables in the form: SELECT * FROM MODELS LEFT OUTER JOIN MODELINFO ON MODELS.MODEL LIKE MODELINFO.REGEX.  There are already a huge number of permutations of the regex matches needed to cover my model data.  Inability to use an optional character in the regex will add a lot of work and double up a lot of rows.
0
need a regular expression that will check and remove a space before and after a comma and remove the comma if value is null following the comma.  

Data                   Expected Results
------------             --------------
CHN, USA             CHN,USA
CHN , USA            CHN,USA
CHN,USA              CHN,USA
CHN,                     CHN
CHN ,                    CHN
CHN , USA, LBB   CHN,USA,LBB
0
I have a string like a subject in an email: customer needs tank pumped [12345]

I need to use a regular expression to extract the value withing the right/left brackets.  This is the unique ID for the message.

I would like to know the most efficient way to do it.

Thanks
0
Hi All,

Hope your well,

I have a VB script which is nearly there but just a small part missing.

The script is being configured to delete certain contacts with a particular attribute set. Within that subset of contacts with this particular attribute im also adding some additional logic to not delete all of them e.g.

as an example: I look for contacts with extensionattribute1 set with "SPECIALATTRIBUTE", I then say, if email address 2 is populated DO NOT DELETE, move on to the next. My aim is to delete all of these contacts without an email address 2 set. The bit where im stuck is that I'm also trying not to delete contacts that have a certain domain e.g outlook.com but im not sure on the contains context. My ultimate goal is to look for contacts with a particular attribute, keep the ones that have an Email2address set and if their email1address contains outlook.com and then delkete the rest that do not match these conditions.


Set objRecord = objItem.Find("[Extensionattribute1] = ""SPECIALATTRIBUTE""")

While Not objRecord Is Nothing
      
      If objRecord.Email2Address = "" And objRecord.Email1Address <> "*OUTLOOK.com" Then objRecord.Delete

      Set objRecord = objItem.FindNext

Many Thanks.
0
I need a regular expression that will remove all spaces from a string including leading and training spaces.  

Data:                         Expected Result
 L P M                       LPM
    LPM                      LPM
LPM                          LPM
L PM                         LPM    
L   P M                      LPM   (double space example)
1 0 0 0                      1000
0
Need help with a regual expression to extract numeric values including period in front of certain words.  I just need to get the number values in front of word "GPM", "LPH" or "GPH".  

.*?((\d+\.\d+|\.\d+|\d+)*\s*GPM"LPH|GPH).*    ---> i tried this but does not work.

Data:                      Expected Results
----------------           ------------------------
1.2 GPM                1.2
400 lph                  400
X GPM                   (nothing)
12 XXX                   (nothing)
321 X GPM           321
GPM 660              (nothing)
1.2GPM                1.2
6lph                      6  
23.8lphgpm        23.8
0
I need help with a regex to check for a letter and space following.  I need to replace all the spaces between letters "G, L, P, M, H, S".  

Data:            Results
--------------    ------------
1.2 G P M     1.2 GPM
99 L P M        99 LPM    
1.5 L P S        1.4 LPS
88 G P S        88 GPS
0
I need help with a regular expression to extract digits and certain words from a string.  I need to extract all digits, including a period plus GPH, LPM or LPH.  

Data:                        Regex
-------------
1.2 GPM                   1.2
1.2 GPH                   1.2 GPH
1.2 XYZ                    1.2
1.2GPH                    1.2GPH
1.2 LPM                   1.2 LPM
1.2 LPH                    1.2 LPH
1 LPH                        1 LPH
LPM                          LPM
XYZ 1                         1
0
I need help with a regular expression that will only pick up the number preceding a certain word "GAL".  I need to pick up only the number up to the first space or /.

Data                                                                   Expected Results:
-----------------------------------                                ---------------------------
55 GAL DRUMS T PLUS 2                                55
Test 10 GAL DRUMS T PLUS 2                       10
200 500 1 GAL                                                  1
GAL 100 DRUM                                                [nothing]
100 KW/500 GAL Drum                                  500
XX GAL                                                              [nothing]
X1 GAL                                                              1
0
Angular Fundamentals
LVL 19
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

I need help with a regular expression that will check a string for "UL" and followed by a number or a space and a number

Data                                                       Expected Result
---------------------------                              ---------------------------
UL 4                                                        True
ULXX                                                       False
UL7                                                         True
Z89                                                          False
UL/5                                                        False
Test UL5X                                              True
7UL                                                         False
8UL9                                                       True
UL-9999                                                  False
0
I need a regular expression that will extract all the values preceding certain words like "Handle" or "Frame"

Data                                          Result
---------------------                       -------------
5 Handle                                   5
Steel Blue HANDLE                Steel Blue
6 Handles                                6
Handle                                     [nothing]
Ivory frame                             Ivory
two handle knob                    two
0
I need a regular expression that would extract the values preceding the second occurrence of a "X" up to the first occurrence of "X".  

Data
------------------
4 X 5 X 6                 ---->  5
Test X  by 1 X        -----> by 1
3 X 5                       ------> Nothing.  
3 X 10 X 6 X 6 X       ------> 10
XXX                           ------> Nothing
X X X                         ------> Space    (excluding spaces would be ideal)
9 x 9 x                      --------> 9
0
I need a regular Expression that will find 2 "X"'s  with a  number preceding each "X" .  Basically i am looking for package dimensions in a string.    So again the string must contain only 2 "X"  and each "X" must have a numeric value preceding it.

Data
________________
3 X 5 X 6                                      ----> Match
3 5 X 6                                         -----> No Match
Inner Pack 5.6 X 5.1 X 6            ----> Match
5 X 6.8 X 3 1/5                            ----->Match
5 1/4 x 1/4 X 5.0                        ------>Match
4 X 6 X 7 X 8                               ------->Not Matched
X   / X                                          -------> No match
3.0X4x8.0                                   ------->Match
0
Hi, I would like to add a custom validation field to my registration page.

The number shall be of the format

#####-#######-#

My intention is to let the user type the numbers and let the hyphens fit in themselves.

I am using Ultimate Member plugin.
1
How would I go about deleting a line of text using regular expression?

Also, how can I delete a line following found character in textpad by using regular expression?
1
I need to query an html dump using javascript and find all matches for a specific text and create a div with that information.

I seem to be really stuck on how to even start.

I want to be able to loop thru and create a div based on the values:
e.g <div style="height:(whatever the first height value is from the loop")><a href = (product id from first loop)>click here</a>


Attaching the html dump


   
 <div class="div class">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>List #</th>
                    <th>Product </th>
                    <th>Description</th>
                    <th>Price</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <tr style="height: 50px;">
                    <td>1</td>
                    <td>TD Info</td>
                    <td>TD Info2</td>
                    <td>1</td>
                    <td><a href="/products/detail?id=1">cick here</a></td>
                </tr>
                <tr style="height: 52px;">
                    <td>2</td>
                    <td>TD Info</td>
                    <td>TD Info2</td>
                    <td>9</td>
                    <td><a href="/products/detail?id=12">cick here</a></td>
                </tr>
            </tbody>
        </table>
    </div>

Open in new window

0
Hi all,

 How to compare string within an array? That string contains backslashes, colon and paranthesis.

sample program:

use strict;
use warnings;

sub perl_func {
    my ($z, $x) = @_;

    print "\n";
    print "z: $z\n\n";
   
    my @lx=@$x;
    foreach my $tx (@lx)
    {
       
        if ($z !~ m|$tx|)
        {
            print "$z !~ $tx\n";
        }
        else
        {
            print "$z == $tx\n";
            return 1;
        }
    }
   
    print "\n";
    return 0;
   

}

#my @x = ("One", "Two", "Three", "Four", "Five");
#my $z = "Four";
#works fine for above x & z

my @x = ("One\\OnesPosition:Num (NumPerl)", "Two\\TensPosition:Num (NumPerl)", "Three\\HundresPosition:Num (NumPerl)", "Four\\ThosandsPosition:Num (NumPerl)", "Five\\TenThousPosition:Num (NumPerl)");
my $z = "Four\\ThosandsPosition:Num (NumPerl)";


if(perl_func($z, \@x))
{
    print "\nfound element\n";
}
else
{
    print "\nnot found element\n";
}
0
Hi Experts,

I am using SSRS and I want to create a subtotal on based on the first 7 character of the AccountID field.

So the example attached, I would have a subtotal for the account 101-002-xx,  101-007-xx and 102-002-xx.

Screenshot_1.png
0
Expert Spotlight: Joe Anderson (DatabaseMX)
LVL 19
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.

Hi,
I'm fairly new to php and mysql but I'm creating a PHP and MySQL web application for a client. I have a register.php page with the following form fields:
Contact Name, Phone, Email, Password, Confirm Password, Ticket Holder Password and Ticket Holder Confirm Password, where Users can register/sign up to use the app. Once they do register, they get redirected to admin_login.php page where they can login and get full access to the app and various other pages I've created.

My Problem:
My Password validation functions aren't working and I'm not sure why. I want the passwords to be a minimum of 8 characters, contain one upper and lowercase letter, a number and a special character. I'm using a regular expressions code that I found online. What I want is to validate the Password fields, so if the User enters a password that meets the criteria mentioned above than it should INSERT the data INTO the database, if it doesn't meet the Password criteria mentioned above I want to display an error message saying: "Password must be minimum of 8 characters, contain one upper and lowercase letter, a  number and a special character". I'm new to using php functions and how to call them properly.

This is the code in my functions.php page:

<?php

// FUNCTIONS.php

// clean the form data to prevent injections

/* Built in functions used:
   trim()
   stripcslashes()
   htmlspecialchars()
   strip_tags()
   str_replace()
*/

function validateFormData($formData) {

Open in new window

0
I have a long text that has this string$

.... value="variablechars" .....

or
.... value='varchars'....

I need to implement a regular expression in asp to extract these strings and create a list (each record with 2 items)

Once extracted I have no problem in creating the list in my database

the list

name1, value="str1"
name2, value="str2"
name3,value="str3"

name4,value='str4'
name5,value='str5'
name6,value='str5'

I extract email with this code (asp)

Set RegularExpressionObject = Server.CreateObject("VBScript.RegExp")
With RegularExpressionObject
 .Pattern = "[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+"
 .IgnoreCase = True
 .Global = True
 End With

 StringToSearch = blocks(x)
 set objMatches = RegularExpressionObject.Execute(StringToSearch)
 for each objMatch in objMatches
 email=objMatch.value
 next

Also extract  strings as

&nbsp;Actividad <br/>

I guess I am missing the Pattern

Example

<img src="image.png" />&nbsp;Actividad <br/><input type="text" readonly class="textboxif" style="width: 410px;" value="Name of activity" name="sector" id="sector"/></td><td>

Here the items would be

Actividad,Name of activity

I have many atrings that I have to extract the data from

Any ideas?
0
I need a Regex which can convert this character   to ' in PHP.
Looking forward for help.

Thanks
0
Im trying to write a jQuery validation method, but having issues getting the RegEx to match up.

Im trying to match a 16 character string, which has to be uppercase.
First 5 characters need to be A-Z
Next 6 characters are numeric
Next 2 charachers are A-Z
Last 3 characters can be A-Z or 0-9

So I got the following regex statment:-
5[A-Z]6[0-9]2[A-Z]3[[A-Z]|[0-9]

However when I run it thought an online checker it says it has matched 8, where surely it should say its matched 1, I can then put into my jQuery to say if the match == 1 then its good else there is a problem.

Any ideas what Im doing wrong, or am I miss understanding something here?
0
I am using CMS to build HTML pages. All the html content is saved in Database. That HTML code contains text, formatted html and images etc.
Each image has <img> tag.

I am using Sphinx Full Text Search. I have make an index of the column which contains HTML of the page.

Here is my code


include 'C:\Sphinx\api\sphinxapi.php';

// Build search query
$cl = new SphinxClient();

$cl->SetServer( "localhost", 9312 );
$cl->SetMatchMode( SPH_MATCH_EXTENDED  );
$cl->SetRankingMode ( SPH_RANK_SPH04 );

$q  = '"' . $cl->EscapeString($_REQUEST['input']) . '"/1';
$searchresults = $cl->Query($q, 'my_index' );

if (!isset($searchresults["matches"]) )
{
	print("No Result Found");
	exit();
}


foreach($searchresults["matches"] as $match)
{

  $entry = array("title" => "");
  if(isset($match["attrs"]))
  {
        "<br>".$entry["title"] = (isset($match["attrs"]["title"]) ? $match["attrs"]["title"] : "");	
	$entity["entity_id"]  = (isset($match["attrs"]["entity_id"]) ? $match["attrs"]["entity_id"] : "");
	
						// Getting Link //
	$qry = "select * from url_alias where source like 'node/$entity[entity_id]'";
	$rst = mysqli_query($conn,$qry) or die(mysqli_error());
	$rst_fieds = mysqli_fetch_array($rst);
	$url_alias_link = $rst_fieds['alias'];
	   
	$entry["bundle"] = (isset($match["attrs"]["field_body_value"]) ? $match["attrs"]["field_body_value"] : "")."<br>";
	$entry["bundle2"] = strip_tags(html_entity_decode($entry["bundle"]));
	
		print "<div class='search-web'><a 

Open in new window

0
Help me to fetch first 3 lines of my email body by regular expression
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.