How to only match a single instance of a character?

前端 未结 3 2084
你的背包
你的背包 2021-01-24 16:23

Not quite sure how to go about this, but basically what I want to do is match a character, say a for example. In this case all of the following would not contain ma

3条回答
  •  悲哀的现实
    2021-01-24 17:15

    You need two things:

    • a negated character class: [^a] (all except "a")
    • anchors (^ and $) to ensure that the limits of the string are reached (in other words, that the pattern matches the whole string and not only a substring):

    Result:

    ^[^a]*a[^a]*$
    

    Once you know there is only one "a", you can use the way you want to extract/replace/remove it depending of the language you use.

提交回复
热议问题