简体   繁体   中英

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

您可以使用此正则表达式通过在字符串末尾查找Z来提取所需的字符。

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM