duankanyi6539 2017-12-08 18:51
浏览 24
已采纳

正则表达式只更改div内的数字[关闭]

I have this regex for now

/<div[^>]*>|(\d{1,9}\.\d{2})/

which detect the opening of a <div> and group the number in a currency format inside it.

If I have a string like this

<div class="foo">Hello world 4546.00 and 6596.45 bla bla bla</div>

I would like to only replace the numbers inside it with a preg_replace

As you can see in the example below, I don't want the number outside of the div to be selected, only ones inside.

https://regex101.com/r/AZd896/1/

  • 写回答

2条回答 默认 最新

  • dragon8002 2017-12-08 18:59
    关注

    Brief

    I'm not sure why you got downvoted so quickly, but I can only assume it's because of this question's topic and its relationship with regex match open tags except xhtml self contained tags.

    By no means is this the best answer, but, in the scope of your question, it does solve your issue.


    Code

    See regex in use here

    (?:<div[^>]*>|\G(?!\A))(?:(?!</div>).)*?\K\d{1,9}\.\d{2}
    

    If the <div> tag might span multiple lines, you can add the s modifier to allow . to match newline characters as seen here.


    Results

    Input

    dasdfasdf 355.56 asdfasd
    <div class="sdaf">sdfsad 36546545643.00 asdfa sdf sadfasdf 544.45 sadfs</div>
    dasdfasdf 355.56 asdfasd
    

    Output

    dasdfasdf 355.56 asdfasd
    <div class="sdaf">sdfsad 36 asdfa sdf sadfasdf  sadfs</div>
    dasdfasdf 355.56 asdfasd
    

    Explanation

    • (?:<div[^>]*>|\G(?!\A)) Match either of the following
      • <div[^>]*> Match the following
        • <div Match this literally
        • [^>]* Match any number of any character not present in the set (anything except >)
        • > Match this literally
      • \G(?!\A) Assert position at the end of the previous match
    • (?:(?!</div>).)*? Tempered greedy token matching any character any number of times, but as few as possible, and ensuring not to match </div>
    • \K Resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match.
    • \d{1,9}\.\d{2} Match 1-9 digits, followed by a literal dot ., followed by exactly 2 digits
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口