简体   繁体   English

Javascript正则表达式从中间字符串中提取字符,并带有可选的结束字符

[英]Javascript regular expression to extract characters from mid string with optional end character

I would like to extract characters from mid string with optional end character. 我想从中间字符串中提取带有可选结束字符的字符。 If the optional end character is not found, extract until end of string. 如果找不到可选的结束符,请提取到字符串末尾。 The first characters are S= and the last optional character is &. 前一个字符为S =,最后一个可选字符为&。

Example #1: 范例1:

"rilaS=testingabc"

should extract: 应该提取:

"testingabc"

Example #2: 范例2:

"rilaS=testing123&thistest"

should extract: 应该提取:

"testing123"

This is what I have so far (Javascript): 到目前为止,这是我所拥有的(JavaScript):

var Str = "rilaS=testing123&thistest";
var tmpStr = Str.match("S=(.*)[\&]{0,1}");
var newStr = tmpStr[1];
alert(newStr);

But it does not detect that the end should be the ampersand (if found). 但是它没有检测到结尾应该是“&”号(如果找到)。 Thank you before hand. 先谢谢你。

Answer (By ggorlen) 答案(通过gorgoren)

var Str = "rilaS=testing123&thistest";
var tmpStr = Str.match("S=([^&]*)");
var newStr = tmpStr[1];
alert(newStr);

You may use /S=([^&]*)/ to grab from an S= to end of line or & : 您可以使用/S=([^&]*)/S=抓取到行尾或&

 ["rilaS=testingabc", "rilaS=testing123&thistest"].forEach(s => console.log(s.match(/S=([^&]*)/)[1]) ); 

Just in case you are wondering why your original regex didn't work: the problem is that the (.*) pattern is greedy - meaning it will happily slurp up anything, including &, and not leave it for for later items to match. 以防万一,您想知道为什么原来的正则表达式不起作用:问题是(。*)模式贪婪 -意味着它会愉快地吞噬包括&在内的所有内容,并且不留给以后的项目匹配。 This is why you want the "not &" - it will match up to, but not including the &. 这就是为什么您想要“ not&”的原因-它可以匹配,但不包括&。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM