1

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.

1
  • [ad_] matches one of a, d, or _. If you want to match the whole string it’d be ad_; (?:ad_)? matches ad_ zero or one time. Commented Dec 4, 2017 at 11:34

2 Answers 2

3

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 _

Sign up to request clarification or add additional context in comments.

Comments

2

My suggestion would be to use this regex string:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.