简体   繁体   English

REGEX:构造涉及可选字符的正则表达式

[英]REGEX: construct regex involving optional characters

I am trying to construct regex on the following patterns 我正在尝试在以下模式上构建正则表达式
1. abc 24 defZ 1. abc 24 defZ
2. abc lmnZ 2. abc lmnZ
3. pqrZ 3. pqrZ

The idea here is to extract characters preceding Z in that word. 这里的想法是提取该单词中Z之前的字符。 Z is the constant characters where the rest are random characters. Z是常量字符,其余为随机字符。 For the examples shown above, I need the following 对于上面显示的示例,我需要以下内容
1. def 1. def
2. lmn 2. lmn
3. pqr 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匹配一个或多个非空格字符。

\S+(?=Z)

OR 要么

This also matches an empty string exists before Z in this foo Zbar string. 这也匹配此foo Zbar字符串中Z之前存在的空字符串。

\S*(?=Z)

OR 要么

Use capturing group. 使用捕获组。

(\S+)Z

DEMO 演示

If you want to extract only letters then use 如果您只想提取字母,请使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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