Regex to match a string with specific start/end

不打扰是莪最后的温柔 提交于 2019-12-02 08:08: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 and I want all options mentioned (e.g. --option).

I'm working with Sublime Text and according to its cheatsheet they support \A and \Z to denote start and end of strings.

Thus, I thought \A--.* \Z should match all strings, starting with -- and ending with .

However, this doesn't match anything at all.

What regex would match all strings, starting with a double dash and ending with a space character? Any occurrence, independent of its position should be matched.


回答1:


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.




回答2:


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




回答3:


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;
  }
};


来源:https://stackoverflow.com/questions/43340718/regex-to-match-a-string-with-specific-start-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!