regex to match entire words containing only certain characters

后端 未结 4 1353
無奈伤痛
無奈伤痛 2021-01-18 06:01

I want to match entire words (or strings really) that containing only defined characters.

For example if the letters are d, o, g

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 06:35

    Depending on the language, this should do what you need it to do. It will only match what you said above;

    this regex:

    [dog]+(?![\w,])
    

    in a string of ..

    dog god ogd, dogs o
    

    will only match..

    dog, god, and o
    

    Example in javascript

    Example in php

    Anything between two [](brackets) is a character class.. it will match any character between the brackets. You can also use ranges.. [0-9], [a-z], etc, but it will only match 1 character. The + and * are quantifiers.. the + searches for 1 or more characters, while the * searches for zero or more characters. You can specify an explicit character range with curly brackets({}), putting a digit or multiple digits in-between: {2} will match only 2 characters, while {1,3} will match 1 or 3.

    Anything between () parenthesis can be used for callbacks, say you want to return or use the values returned as replacements in the string. The ?! is a negative lookahead, it won't match the character class after it, in order to ensure that strings with the characters are not matched when the characters are present.

提交回复
热议问题