benjamin54
benjamin54

Reputation: 1300

Regex expression for a string pattern

Regex newbie here. I need to create a regex expression that will support following strings:

<optional constant string 1><string 2><space><string 3>

Here constant string 1 is: ad_

Ex (allowed patterns).

[1]
ad_xyz.qwe.sty blah blah...
string 1: ad_
string 2: xyz.qwe.sty
string 3: blah blah... (free text)

[2]
abc blah ...
string 1: (absent)
string 2: abc
string 3: blah ... (free text)

[3]
sdf.pqr blah blah blah...
string 1: (absent)
string 2: sdf.pqr
string 3: blah blah blah... (free text)

Here is what I'm doing:

(?:[ad_]{0,1})?\-[a-zA-Z.]*\.[a-zA-Z0-9]*

Now this detects only first pattern. Though I have mentioned {0,1}, still string 1 is mandatory.

Upvotes: 1

Views: 82

Answers (2)

iceberg
iceberg

Reputation: 596

My suggestion would be to use this regex string:

^(ad_)?(\S*)\s(.*)

Upvotes: 2

anubhava
anubhava

Reputation: 785146

You can use this regex for an optional match in first group:

^(ad_)?(\w+(?:\.\w+)*)\s*(.*)$

RegEx Demo

In your regex [...] makes it character class where only one character out of several character matches at a time so [ad_] match any one of a or d or _

Upvotes: 3

Related Questions