正则表达式获取两个字符串之间的字符串

时间:2014-07-11 23:48:03

标签: javascript regex

我有这个字符串:

# userid name uniqueid connected ping loss state rate
# 529 2 "arioch83" STEAM_1:0:86796179 55:58 99 0 active 80000
# 619 3 "Snake" STEAM_1:0:27678629 06:42 61 0 active 80000
# 622 4 "Captain_Selleri" STEAM_1:1:47927314 03:25 44 0 active 80000
# 583 5 "krN[786]" STEAM_1:1:14638235 28:53 53 0 active 128000
# 621 6 "Giack" STEAM_1:1:67468100 04:44 129 0 active 80000
# 326 7 "Urkrass" STEAM_1:0:55150382  3:02:31 51 0 active 80000
#613 "Vinny" BOT active
# 584 9 "Tkappa" STEAM_1:0:32266787 27:55 360 0 active 80000
# 605 10 "Narpok19" STEAM_1:0:44838130 14:36 67 0 active 80000
# 551 11 "robbetto83" STEAM_1:1:63675894 50:10 86 0 active 80000
# 530 12 "XxKazuyaxX" STEAM_1:0:18676379 55:57 68 0 active 80000
# 623 13 "beut3d - Keyser Söze" STEAM_1:0:14500718 00:29 70 0 active 80000
# 602 15 "Homroy" STEAM_1:1:7870901 16:34 169 0 active 80000
# 607 16 "[Bloody]Eagle" STEAM_1:1:59567346 09:14 77 0 active 80000
#615 "Jeff" BOT active
# 587 18 "Heisenberg" STEAM_1:1:61427218 25:15 81 0 active 80000
#end

我想在"#userid name uniqueid连接ping丢失状态率"之间得到字符串。和" #end"。我尝试了几个正则表达式基于我在stackoverflow上找到但没有工作:( 这是我的最后一次尝试

var matches = text.match(/# userid name uniqueid connected ping loss state rate(.+)\&#end/);
                if (matches.length > 1) {
                    alert(matches[1]);
                }

正如你所看到的,我对正则表达式一无所知......关于那些的任何好的tuto?

感谢,

4 个答案:

答案 0 :(得分:5)

您需要能够跨多行匹配。您正在寻找s dotall )修饰符。不幸的是,这个修饰符不存在于JavaScript中。常见的解决方法是使用以下内容替换点.

[\S\s]    

因此,您可以使用以下正则表达式:

/# userid name uniqueid connected ping loss state rate([\S\s]*?)#end/

<强>解释

(               # group and capture to \1:
  [\S\s]*?      #   any character of: 
                #    non-whitespace (all but \n, \r, \t, \f, and " "), 
                #    whitespace (\n, \r, \t, \f, and " ") 
                #    (0 or more times matching the least amount possible)
)               # end of \1

JavaScript Demo

答案 1 :(得分:0)

使用正则表达式的另一种方法是将字符串拆分为\n并提取所需的部分(从第二行到第二行到最后一行的所有内容):

var contents = "your contents here...";

var contentArray = contents.split( "\n" );

// extract the array elements from the second to the second from last and re-join with `\n`
console.log( contentArray.slice( 1, contentArray.length - 2 ).join( "\n" ) );

答案 2 :(得分:0)

获取#userid#end

未启动的所有行
/^(?!#\s*(userid|end)).*/gmi

Online demo

答案 3 :(得分:0)

您可以使用此模式使用“#end”位于一行开头的事实:

/# userid name uniqueid connected ping loss state rate\n((?:.*\n)*?)#end/

但另一种有效的方法是将日志拆分为行并查看结果列表中的起始行和结束行。