只有当该模式恰好出现一次时,正则表达式才能匹配模式吗?(Can regex match a pattern only if that pattern appears exactly one time?

编程入门 行业动态 更新时间:2024-10-26 18:30:28
只有当该模式恰好出现一次时,正则表达式才能匹配模式吗?(Can regex match a pattern only if that pattern appears exactly one time?)

举个例子:

string1 = "aaxadfxasdf" string2 = "asdfxadf" string3 = "sadfas"

我需要一个匹配x的模式,使得它仅为string2返回x的匹配。

注意:出于这个问题的目的,我必须使用java正则表达式。 此外,我无法访问代码,因此我不能简单地检查java regex对象返回的匹配数。


大家好,

感谢您的回复,其中一些确实回答了我的问题。 我的例子并不像我需要的那样具体。 所以让我把这个怪癖添加到混合中:

如果我匹配多个字符怎么办?

string4 = "This is a sentence!" string5 = "This is just another sentence with some repetition in it. This is a sentence" string6 = "this is"

在这种情况下,我只想在字符串中出现一次时才匹配“句子”。

此外,虽然未在示例中表示,但我需要能够跨行搜索。

Take this example:

string1 = "aaxadfxasdf" string2 = "asdfxadf" string3 = "sadfas"

i need a pattern that matches x such that it returns a match for x only for string2.

Note: for the purpose of this question, i must use java regex. Also, i don't have access to the code, so i can't simply check the # of matches returned by the java regex object.


Hey All,

Thanks for the responses, some of which do answer my question. My example wasn't as specific as i needed it to be. So let me add this quirk to the mix:

what if i'm matching more than a single character?

string4 = "This is a sentence!" string5 = "This is just another sentence with some repetition in it. This is a sentence" string6 = "this is"

In this case, i want to match "sentence" only if it appears in the string only once.

Also, though not represented in the example, i need to be able to search across lines.

最满意答案

^[a-wy-z]+x[a-wy-z]+$

我不确定你是否只是期待字母,或者你想要匹配的x之前和之后是否包含符号和数字。 如果是这样,请使用[^x]而不是[a-wy-z] ,如下所示:

^[^x]+x[^x]+$

如果您还希望自己匹配x ,请将+符号替换为*如下所示:

^[a-wy-z]*x[a-wy-z]*$ ^[a-wy-z]+x[a-wy-z]+$

I'm not sure if you are only expecting letters, or if symbols and numbers might be included before and after the x you want to match. If so, use [^x] instead of [a-wy-z], like so:

^[^x]+x[^x]+$

If you are also wanting to match x by itself, replace the + symbols with * like so:

^[a-wy-z]*x[a-wy-z]*$

更多推荐

本文发布于:2023-08-06 16:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   正则表达式   regex   match   appears

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!