提高 Java 正则表达式的性能

发布于 2024-12-28 04:31:31 字数 522 浏览 3 评论 0原文

我正在寻找一种方法来改进这个正则表达式:

^(?:([^.]+).?){6}_tid

这会提取 point.separated.string.of.当中任意长度的第 6 个字段,直到“_tid”

所以如果它看起来像这样:

mc11_7tev.138345.dgnol_tb6_m12u_140_140_110_2l_jimmy_susy.evgen.log.e825_tid431423_0

它应该返回

e825

足够有趣,如果我删除了正则表达式 ^(?:([^.]+).?){6} 的 _tid 部分,我得到了我正在寻找的性能......一百万秒需要 1 到 2 秒要检查的字符串。 使用 _tid.. 最多需要 5 分钟。

有更好的方法吗?


编辑: 啊,我忘了提,这是在 Apache Pig 中,所以所有内容都应该在正则表达式子句中。

I'm looking for a way to improve this regular expression:

^(?:([^.]+).?){6}_tid

This extracts the 6th field of a point.separated.string.of.arbitrary.lengths up to "_tid"

So if it looks like this:

mc11_7tev.138345.dgnol_tb6_m12u_140_140_110_2l_jimmy_susy.evgen.log.e825_tid431423_0

it should return

e825

Funnily enough, if I remove the _tid part of the regex ^(?:([^.]+).?){6}, I get the performance I was looking for.. 1 to 2 seconds for a million strings to check.
With the _tid.. it takes up to 5 minutes.

Is there a better way to do this?


EDIT:
Ah, I forgot to mention, this is in Apache Pig, so everything should be in the regex clause.

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

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

发布评论

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

评论(4

大海や 2025-01-04 04:31:31

您忘记转义点,请尝试

^(?:([^.]+)\.?){6}_tid

这种方式,您的正则表达式匹配的可能性要少得多。这 ”。”不转义匹配任何字符(没有换行符)。

我看到的另一种可能性是去掉可选的点。

^(?:[^.]+\.){5}([^.]+)_tid

请参阅 Regexr 上的此处

You forgot to escape the dot, try this

^(?:([^.]+)\.?){6}_tid

this way your regex has much less possibilities to match. The "." without escaping matches any character (without line break characters).

The other possibility I see is getting rid of the optional dot

^(?:[^.]+\.){5}([^.]+)_tid

See it here on Regexr

仙女山的月亮 2025-01-04 04:31:31

我首先将字符串拆分为 .,获取第六部分,将其拆分为 _,获取第一部分:

s.split("\.")[5].split("_")[0];

未测试!

I would first split the String on ., get the 6th part, split it on _, get the first part:

s.split("\.")[5].split("_")[0];

Not tested!

孤君无依 2025-01-04 04:31:31

这个似乎比你的跑得快:

^(?:[^.]+\.){5}([^.]+)_tid

This one seems to run faster than yours:

^(?:[^.]+\.){5}([^.]+)_tid
澜川若宁 2025-01-04 04:31:31

这给了我最好的性能结果:

    Pattern p = Pattern.compile(".*\\.([^_]+)_tid.*");

This one gives me the best performance results:

    Pattern p = Pattern.compile(".*\\.([^_]+)_tid.*");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文