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

正则表达式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

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

报告相同问题?