AV94
AV94

Reputation: 1814

How to write optional word in Regular Expression?

I want to write a java Regular expression that recognises the following patterns. abc def the ghi and abc def ghi

I tried this:

abc def (the)? ghi

But, it is not recognizing the second pattern.Where am I going wrong?

Upvotes: 16

Views: 13131

Answers (3)

QuentinJS
QuentinJS

Reputation: 322

Your example worked perfectly well for me in Python

    x = "def(the)?"
    s = "abc def the ghi"
    res = re.search(x, s)

Returns: res -> record

    s = "abc def ghi"
    res = re.search(x, s)

Returns: res -> record

    s = "abc Xef ghi"
    res = re.search(x, s)

Returns: res -> None

Upvotes: 0

Pshemo
Pshemo

Reputation: 124225

Spaces are also valid characters in regex, so

abc def (the)? ghi
       ^      ^ --- spaces

can match only

abc def the ghi
       ^   ^---spaces

or when we remove the word

abc def  ghi
       ^^---spaces

You need something like abc def( the)? ghi to also make one of these spaces optional.

Upvotes: 6

vks
vks

Reputation: 67968

abc def (the )?ghi

           ^^

Remove the extra space

Upvotes: 21

Related Questions