您如何使用现有正则义务的正则表达式检索n个字符?

发布于 2025-02-10 04:06:48 字数 186 浏览 1 评论 0 原文

我需要从电子邮件地址检索电子邮件ID。 (IE

我使用的正则态度是(。*)@。*

现在,我需要用n个字符截断字符串。 (即n = 7 => this-is n = 30 => this-is-the-best.Email)

如何将其添加到现有的正则拨号中? 还有其他建议吗?

I would need to retrieve an email id from a email address.
(i.e. [email protected] => this-is-the-best.email)

The regex that I used is (.*)@.* .

Now I need truncate the string with N characters.
(i.e. N=7 => this-is N=30 =>this-is-the-best.email)

How would I add this to a existing regex?
Any other recommendations?

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

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

发布评论

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

评论(3

栩栩如生 2025-02-17 04:06:48

那:([^@] {1,7})。+

[email protected]
[email protected]

变成:

this-is
short

What about: ([^@]{1,7}).+?

[email protected]
[email protected]

Becomes:

this-is
short
酷遇一生 2025-02-17 04:06:48

我认为这就是您要寻找的:

((.{1,7}).*)@.+

第一个捕获组包含完整的ID,第二组最多包含7个字符。

I think that this is what you are looking for:

((.{1,7}).*)@.+

The first capturing group contains the full id and the second group contains up to 7 chars.

左秋 2025-02-17 04:06:48

在您的模式(。*) @。*中,您不需要尾随。*是可选的,并且点可以匹配任何字符,包括空格和 @它本身可以匹配更多的,只有电子邮件地址。


有趣的是,在实际匹配 @之前,不包括 @ char的非空格字符,在这种情况下,您可以使用匹配7个非Whitespace Chars的捕获组。

([^\s@]{7})[^\s@]*@

模式匹配:

  • ([^\ s@] {7})捕获组1 ,匹配7 non Whitespace chars不包括@
  • [^\ s@]* (可选)匹配任何非whitespace char不包括 @
  • @ 字面上匹配

In your pattern (.*)@.* you don't need the trailing .* as it is optional, and the dot can match any character including spaces and the @ itself which can match much more that just an email like address.


The thing of interest is the non whitespace chars excluding an @ char before actually matching the @, and in that case you can use a capture group matching 7 non whitespace chars.

([^\s@]{7})[^\s@]*@

The pattern matches:

  • ([^\s@]{7}) Capture group 1, match 7 non whitespace chars excluding @
  • [^\s@]* Optionally match any non whitespace char excluding @
  • @ Match literally

Regex demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文