【问题标题】:Regexp matching for some text一些文本的正则表达式匹配
【发布时间】:2011-09-25 17:25:58
【问题描述】:

我有以下文字:

@title1 这里有一些东西,这里有一些@junk@ @新标题 多行。 多行。 多行。 @title3 这里有额外的东西。

我需要一个匹配标题后文本的正则表达式。第一场比赛应该返回

这里有一些东西,这里有一些@junk@

另外,标题是以 @ 开头的新行,后跟一些非空格字符

http://jsfiddle.net/QCNfQ/2/

【问题讨论】:

  • 你已经尝试过哪些正则表达式?为什么他们不工作?
  • 不知道怎么说,匹配所有内容,直到下一组(这将是一个标题)。尝试过类似:/(\n?@\w+\n)([\S\s]*)(?!(\n?@\w+\n))/g,但最后一部分被忽略,它返回标题之后的所有内容。
  • 需要有关适用于文本的格式规则的更多信息。例如,如果标题总是以@title 开头,但其他行从不这样做,您可以使用它,但我们没有足够的信息来假设
  • 编辑问题以反映这一点......不,基本上标题可以是任何单词,它只能由@和换行符分隔。

标签: javascript regex


【解决方案1】:

小提琴http://jsfiddle.net/u5Khe/

您正在寻找此 RE:/(?:^|\n)@([^@\n]+)\s*((?:[\S\s](?!\n@))+)/g

代码:

var string = "@title1\n\nTest @case@ one\n\n@title2\n\nMulti" +
             "\nline\nstring\n\n@title3\n\nfinal test";
var results = [];

var re = /(?:^|\n)@([^@\n]+)\s*((?:[\S\s](?!\n@))+)/g;
var matches = null;
while((matches = re.exec(string)) != null){
    /* matches[0] = whole block
       matches[1] = title
       matches[2] = body
     */
     var body = matches[2].replace(/\^s+|\s$/g,"");
     results.push(body);
}
//results.length will be 3;
alert(results.join("\n-----------------------\n"));
//Shows an alert with all matches, separated by "\n----------------\n"

RE的解释:

  • (?:^|\n)@ 寻找标题的开头(^@ = "@ at the beginning of a text", \n@ = "@ at the beginning of a new line"
  • ([^@\n]+) 表示:匹配除 @ 或换行符(标题分隔符,由 OP 定义)以外的所有字符
  • ((?:[\S\s](?!\n@))+) 表示:选择所有+ 字符\S\s,后面没有换行符+@@(?!\n@)
  • /g 是“全局”标志 = “尝试在给定字符串上获得尽可能多的匹配”

你的字符串应该这样格式化:

@title
Body

@title2
Anything, from @ to @, as long as the next line doesn't start with a @
 @ (There's a whitespace before this @)

@custom title@ Delimited by the @

@Foo
bar

【讨论】:

    【解决方案2】:

    你也许可以这样做:

    /(@title\d)(\s)*(.*)/gi;

    然后访问第三个 ($3) 组。

    所以...

    var a = "@title1\n\nSome stuff here and some @junk@";
    var a1 = "@title2\n\nExtra stuff here.";
    
    var b = /(@title\d)(\s)*(.*)/gi;
    var c = a.replace(b, '$3');
    var d = a1.replace(b, '$3');
    
    document.write(c + '<br />' + d);
    

    示例: http://jsfiddle.net/jasongennaro/5Chjf/

    fyi...这假设@title 每隔一行开始。

    【讨论】:

      【解决方案3】:

      试试这个:

      var text = "@title1
      
      Some stuff here and some @junk@
      
      @title2
      
      Extra stuff here."; 
      
      var output = text.replace(/([^@]+@)(\w+@)/,
                  function (all, g1, g2) {
                      return [g2, g1].join('');
                  }
          );
      
      alert(output)
      

      【讨论】:

        【解决方案4】:

        试试这个

        '\n@title1 test'.match(/(?:\n@title\d)(?:[\s|\n])*(.*)/)[1]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多