没有中间表达式重复的正则表达式 (axb|cxd)

发布于 2024-12-17 23:01:49 字数 245 浏览 5 评论 0原文

我只是不断地碰壁,我无法解决它。我试图获取一个执行为:

(axb|cxd)

except 的正则表达式,但不在表达式中重复 x (因为它是非常长的编码匹配表达式)。这是针对一个大字符串进行测试的,我只需要匹配 x 来进行字符串替换,因此零宽度向前/向后查找是一个选项。有什么想法吗?

a、b、c 和 d 相当小,因此如果可以使表达式更容易形成,则它们可以重复。

提前致谢。

I am just continuously hitting a wall with this one, I cannot solve it. I am trying to get a regex that executes as:

(axb|cxd)

except without repeating x in the expression (as it is really long encoding-matching expression). This is tested against a large string where I only need to match x for string replacement, so zero-width lookahead/behind is an option. Any ideas?

a,b,c, and d are reasonably small, so they can repeat if it makes the expression easier to form.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月亮是我掰弯的 2024-12-24 23:01:49

如果您确实不想在正则表达式中重复 x,那么您必须应用一些手动搜索逻辑。您可以使用正则表达式搜索 x,然后根据找到它的位置,在其前面查找 a,在其后面查找 b,或者在其前面查找 c,在其后面查找 d。但是,这可能比像 Gabe 的答案那样在正则表达式中重复它需要更多的工作。

例如,您可以这样做:

var re = /(a|c)x(b|d)/;
var matches = str.match(re);
if (matches) {
    // exclude axd or cxb
    if ((matches[1] + matches[2]).match(/ab|cd/)) {
        // found axb or cxd
    }
}

但是,老实说,似乎包含 x 两次并让正则表达式引擎为您完成肮脏的工作会更容易:

if (str.match(axb|cxd)) {
    // found match
}

或者,如果将 x 放入字符串两次太麻烦,然后使用 javascript 字符串数学自行构建正则表达式:

var x = "long complicated regex";
var re = new RegExp("a" + x + "b|c" + x + "d");
if (str.match(re)) {
    // found match
}

If you really don't want to repeat x in the regular expression, then you'll have to apply some manual search logic. You can search for x with the regular expression and then, based on where it was found, look for a before it and b after it or c before it and d after it. But, that would likely be more work than just repeating it in the regular expression as in Gabe's answer.

For example, you could do this:

var re = /(a|c)x(b|d)/;
var matches = str.match(re);
if (matches) {
    // exclude axd or cxb
    if ((matches[1] + matches[2]).match(/ab|cd/)) {
        // found axb or cxd
    }
}

But, honestly, it seems like it would just be easier to include x twice and let the regex engine do the dirty work for you:

if (str.match(axb|cxd)) {
    // found match
}

Or, if it's too cumbersome to put x in the string twice, then build the regex yourself using javascript string math:

var x = "long complicated regex";
var re = new RegExp("a" + x + "b|c" + x + "d");
if (str.match(re)) {
    // found match
}
ま柒月 2024-12-24 23:01:49

没有简单的方法可以解决这个问题。你必须做这样的事情:

var x = "long, complicated regular expression";
var re = new RegExp("a" + x + "b|c" + x + "d");

There's no easy way around it. You have to do something like this:

var x = "long, complicated regular expression";
var re = new RegExp("a" + x + "b|c" + x + "d");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文