Regex to match a string with specific start/end

后端 未结 3 1063
深忆病人
深忆病人 2021-01-25 09:57

I\'m trying to match all occurrences of strings starting with -- and ending with a single space .

The file I\'m handling is the OpenVPN manual

相关标签:
3条回答
  • 2021-01-25 10:12

    One thing you can do is add these to .prototype and create your own startsWith() and endsWith() functions

    this way you can do string.startsWith("starts with this"); and string.endsWith("ends with this"); I'm using substring instead of indexOf because it's quicker without scanning the entire string. Also, if you pass in an empty string to the functions they return false. Reference link Here

        if ( typeof String.prototype.startsWith != 'function' ) {
      String.prototype.startsWith = function( str ) {
        return str.length > 0 && this.substring( 0, str.length ) === str;
      }
    };
    
    if ( typeof String.prototype.endsWith != 'function' ) {
      String.prototype.endsWith = function( str ) {
        return str.length > 0 && this.substring( this.length - str.length, this.length ) === str;
      }
    };
    
    0 讨论(0)
  • 2021-01-25 10:24
    foo.*bar
    

    here you will match everything beginning by foo and ending by bar

    then in your case try

    "--.* "
    

    just tested it in sublime text 3 it works

    0 讨论(0)
  • 2021-01-25 10:36

    I think your question caused some confusion due to the use of string. You might want to look up the usage of computer science (e.g. here). What you are looking for is word, starting with -- and ending with a space (or maybe the end of the line).

    You can use (?:^|(?<=\s))--\S+ here.

    • (?:^|(?<=\s)) check that there is a space or the start of a line in front (using a lookbehind)
    • --\S+ match double - and one or more non-space characters
      • note that this will always end at with a space or the end of the line

    Another possibility is (?:^|(?<=\s))--\w+(?=\s|$). Here it looks for a sequence of word characters (letters, digits, underscore) and by a lookahead ensures that it ends with a space or the end of the line.

    0 讨论(0)
提交回复
热议问题