douzhi1919 2015-11-30 11:17
浏览 216
已采纳

正则表达式PHP匹配字符仅在前面或后面跟有相同字符时才匹配。

so I am trying to match a back tick ` but only when it is not more than one in a row:

`test` // matches
``test`` // does NOT match

// does NOT match
```java
    test
```

BUT it needs to also match if is at the beginning of the string or end, so all three must match.

`matches`

Text `matches`

Text `matches`EOL

  • 写回答

1条回答 默认 最新

  • dsla94915 2015-11-30 11:32
    关注

    UPDATE 3

    The regex below matches exactly as the previous one, but consumes the backtick ` avoiding that an ending backtick is considered a starting backtick when the regex engine searchs for the next one.

    (?<!`)`([^`
    ]+)`(?!`)
    

    The correct behaviour (extract only the text wrapped inside single backticks) is keeped using a capturing group `([^` ]+)`.

    Use it with preg_match_all, try this online php demo.

    Legenda:

    • (?<!`)` a backtick not preceded another one
    • `([^` ]+)` a capturing group that matches everything that is not a backtick or a newline (CR or LF)
    • `(?!`) a backtick not followed by another one

    Updated Online Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化