首页 > 解决方案 > Regex Pattern for Matching Single Lines of Text/Chars

问题描述

Say, for the following String, what Regex pattern would I use for matching (and returning an array of matches) for single lines of text/chars (as in starting with characters as opposed to symbols and spaces):

** Header
------------------------------------------------------------

https://www.google.com Google Homepage

Test description for Google homepage

Stack Overflow (https://www.stackoverflow.com)

Test description for Stack Overflow

... when ideally, I want an output like this from using Google Apps Script and RegExp's exec() or String's match():

["https://www.google.com Google Homepage", "Test description for Google homepage", "Stack Overflow (https://www.stackoverflow.com)", "Test description for Stack Overflow"]

Here's the script I have so far:

function testRegex() {
  var test = "** Header\n------------------------------------------------------------\n\nhttps://www.google.com Google Homepage\n\nTest description for Google homepage\n\nStack Overflow (https://www.stackoverflow.com)\n\nTest description for Stack Overflow"
  var regExp = RegExp(".*");
  var matches = regExp.exec(test);

  for each (var match in matches) {
    Logger.log("match: " + match);
  }
}

... which outputs:

match: ** Header
match: 0
match: ** Header
------------------------------------------------------------

https://www.google.com Google Homepage

Test description for Google homepage

Stack Overflow (https://www.stackoverflow.com)

Test description for Stack Overflow

^ Notice how the matches aren't logged individually in single lines.

I've also tried a Regex pattern like RegExp("^[a-zA-Z].*") for only lines starting with characters, but there are no matches.

Or, would I be better off using split() instead? If so, I'd like to exclude lines that start with either symbols or spaces, and get an output like the one I mentioned above.

标签: javascriptregexgoogle-apps-script

解决方案


.* matches a single line of text

^[a-zA-Z].* matches a line that begins by a letter


推荐阅读