简体   繁体   English

正则表达式:确定在第一次出现另一个字符之前是否出现某个字符

[英]Regex: Determine if a character appears before first occurrence of another character

I'm trying to determine whether or not a certain character appears before the first (and only the first) occurrence of another character. 我正在尝试确定某个字符是否出现在另一个字符的第一个(也是第一个)出现之前。

For example, I want to determine whether the character 'X' appears before the first occurrence of 'Y'. 例如,我要确定字符“ X”是否在第一次出现“ Y”之前出现。

The regex would match these: 正则表达式将匹配以下内容:

acXaaccccYaaacacXacacaY // X appears before the first occurrence of Y
aXacacaXacacXavaY // X appears before the first occurrence of Y

The regex would NOT match this: 正则表达式与此不匹配:

acacacaYacacacXacacacY // The X appears after the first occurrence of Y

Is this possible with a single regex match? 单个正则表达式匹配是否可以实现?

You can try something like this: 你可以尝试这样的事情:

^[^Y]*X.*Y.*$

In English, that's "A string of non-Ys, then an X, then anything so long as it contains a Y". 用英语来说,就是“一串非Y,然后是X,然后是任何包含Y的东西”。

It is as simple as this: 这很简单:

^[^Y]*X.*Y

If you need to match the whole input, add .* , ie: ^[^Y]*X.*Y.* 如果需要匹配整个输入,请添加.* ,即: ^[^Y]*X.*Y.*

See a live demo of this working with your examples. 结合示例观看实时演示

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

相关问题 正则表达式:一个字符的最后一次出现和另一个字符的第一次出现之间的匹配 - Regex: match between last occurrence of a character and first occurrence of another character 正则表达式在第一次出现字符之前获取所有内容 - Regex get all before first occurrence of character 使用正则表达式在关键字之前查找第一次出现的字符 - Find first occurrence of a character before a keyword with Regex 正则表达式:字符之前的最后一次出现 - Regex: last occurrence of character before 用另一个字符python正则表达式替换第一个和第三个匹配项 - Replace first and third occurrence with another character python regex 在SQL中用一个字符替换第一次出现的字符,然后用另一个字符替换第二个出现的字符 - Replacing first occurrence of character with one character and the second with another character in SQL 正则表达式:匹配第一次出现的带有字符 'a' 的单词 - Regex: matching up to the first occurrence of word with character 'a' in it 正则表达式 - 如何在第一次出现角色时停止 - regex- how to stop at first occurrence of a character 匹配正则表达式直到第一次出现特殊字符'->' - Match regex until the first occurrence of special character '->' 正则表达式:匹配字符的第一次出现 - Regex: matching up to the first occurrence of a character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM