其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

正则表达式 - 在字符串中查找8位数字[关闭]

GG网络技术分享 2025-03-18 16:15 2


问题描述:

I want to extract 8 digit number from string using regex.

Test strings are

hi 82799162, 236232 (82342450), test data 8979

Required respective output should be

82799162, 82342450, null

I have tried following codes:

  • preg_match(\'/[0-9]{8}$/\', $string, $match);
  • preg_match(\'/\\d{8}$/\', $string, $match);

But it does not retrieve the number from 236232 (82342450).

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

我想使用正则表达式从字符串中提取8位数字。</ p>

测试 字符串是</ p>

hi 82799162 </ code>, 236232(82342450)</ code>, test data 8979 </ code> </ p>

</ blockquote>

所需的相应输出应为</ p>

82799162 </ code>, 82342450 </ code>, null </ code> </ p>

</ blockquote>

我试过以下代码:</ p>

  • preg_match(\'/ [0-9] {8} $ /\',$ string,$ match); </ code> </ li>

  • preg_match(\'/ \\ d {8} $ /\',$ string,$ match); </ code> </ li>

    </ ul>

    但它不会从 236232(82342450)中检索数字 )</ code>。</ p>

    </ div>

    网友观点:

    The problem is with your $ sign, and it is used to indicate the end of your expression. So basically, with that expression, you are looking for a string which ends with a 8 digit number. But in your second test string; \'236232 (82342450)\', ends with a bracket, and therefore it doesn\'t match the criteria (does not end with a number).

    So remove the trailing $ and it will work.

    preg_match(\'/[0-9]{8}/\',$string,$match);

    Hope it helps!!

    If a regex is to capture exactly 8 digits, is must contain:

    • \\d{8} as a central part,
    • a \\\"before\\\" condition, ensuring that no digit occurs before your match,
    • an \\\"after\\\" condition, ensuring that no digit occurs after your match.

    One of possible solutions is to use negative lookbehind / lookahead:

    (?<!\\d)\\d{8}(?!\\d)

    Another option is word boundary assertions (at both ends):

    \\b\\d{8}\\b

    I think, regex like [0-9]{8} is not enough, as it captures also

    first 8 digits from a longer sequence of digits.

    Are you happy with that?

    正则表达式技巧与注意事项

    原创:打码日记(微信公众号ID:codelogs),欢迎分享,转载请保留出处。

    简介

    现如今,正则表达式几乎是程序员的必备技能了,它入手确实很容易,但如果你不仔细琢磨学习,会长期停留在正则最基本的用法层面上。
    因此,本篇文章,我会介绍一些能用正则解决的场景,但这些场景如果全自己琢磨实现的话,需要花一些时间才能完成,或者就完全想不出来,另外也会介绍一些正则表达式的性能问题。

    匹配多个单词

    比如我想匹配zhangsan、lisi、wangwu这三个人名,这是一个很常见的场景,其实在正则里面也算基本功,但鉴于本人初入门时还是在网上搜索得到的答案,还是值得提一下的!
    实现如下:

标签:

提交需求或反馈

Demand feedback