nsregularexpressionqregularexpression

Regular expression


I have a document, and I need to find all the words(no spaces) borded with '. (e.g. 'apple', 'hello') What would be the regular expression?

I've tried ^''$ but it didn't work.

If there isn't any solution, it could not be "any word" but also it can be a word from an order(e.g. apple, banana, lemon) but it still must have the (')s.

Thank you so much

Andrew


Solution

  • If you want to capture single-quoted strings, literally any character run except single-quotes but between the single-quotes, use

    /'[^']+'/

    If you need single words, i.e. alphabetic characters but no spaces, try

    /'[a-zA-Z]+'/

    I'm asssuming a couple things here:

    1. You're using a language that delimits regexes with slashes. This includes Javascript and Perl to my knowledge, and probably a bunch of others. In some other languages, like C#, you should use double quotes to delimit, e.g. "'[a-zA-Z]+'"
    2. You're using a flavor of regex that does not need to escape the plus sign.
    3. You're trying to capture all such words within a long string. I.e., if the input string is "Here is a 'long' string with 'some' 'words' single-quoted" then you will capture three words: 'long','some', and 'words'.