dongtun1683 2012-07-12 13:16 采纳率: 0%
浏览 36
已采纳

如何在字符串中获取带点的数字数据?

There is a string variable containing number data with dots , say $x = "OP/1.1.2/DIR"; . The position of the number data may change at any circumstance by user desire by modifying it inside the application , and the slash bar may be changed by any other character ; but the dotted number data is mandatory. So how to extract the dotted number data , here 1.1.2, from the string ?

  • 写回答

1条回答 默认 最新

  • dongzhi9032 2012-07-12 13:23
    关注

    Use a regular expression:

    (\d+(?:\.\d+)*)
    

    Breakdown:

    • \d+ look for one or more digits
    • \. a literal decimal . character
    • \d+ followed by one or more digits again
    • (...)* this means match 0 or more occurrences of this pattern
    • (?:...) this tells the engine not to create a backreference for this group (basically, we don't use the reference, so it's pointless to have one)

    You haven't given much information about the data, so I've made the following assumptions:

    • The data will always contain at least one number
    • The data may contain only a number without a dot
    • The data may contain multi-digit numbers
    • The numbers themselves may contain any number of dot/digit pairs

    If any of these assumptions are incorrect, you'll have to modify the regular expression.

    Example usage:

    $x = "OP/1.1.2/DIR";
    
    if (!preg_match('/(\d+(\.\d+)*)/', $x, $matches)) {
        // Could not find a matching number in the data - handle this appropriately
    } else {
        var_dump($matches[1]); // string(5) "1.1.2"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)