user1432523
user1432523

Reputation: 199

REGEX: construct regex involving optional characters

I am trying to construct regex on the following patterns
1. abc 24 defZ
2. abc lmnZ
3. pqrZ

The idea here is to extract characters preceding Z in that word. Z is the constant characters where the rest are random characters. For the examples shown above, I need the following
1. def
2. lmn
3. pqr

I know I can use normal string operation but its important that this is the regex. The regex that I have is :

(\s*)?(.*)Z

Thanks for the help

Upvotes: 0

Views: 49

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

You could use this regex which extracts the characters you want by looking ahead for Z at the end of the String.

[a-zA-Z]+(?=Z$)

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Use \S to match one or more non-spacer characters.

\S+(?=Z)

OR

This also matches an empty string exists before Z in this foo Zbar string.

\S*(?=Z)

OR

Use capturing group.

(\S+)Z

DEMO

If you want to extract only letters then use

[a-zA-Z]+(?=Z)

Upvotes: 1

Related Questions