需要正则表达式来查找两个标记之间的子字符串 [英] Need regexp to find substring between two tokens
问题描述
我怀疑这已经在某处得到了回答,但我找不到它,所以...
I suspect this has already been answered somewhere, but I can't find it, so...
我需要从较大字符串中的两个标记之间提取一个字符串,其中第二个标记可能会再次出现,意思是...(伪代码...)
I need to extract a string from between two tokens in a larger string, in which the second token will probably appear again meaning... (pseudo code...)
myString = "A=abc;B=def_3%^123+-;C=123;" ;
myB = getInnerString(myString, "B=", ";" ) ;
method getInnerString(inStr, startToken, endToken){
return inStr.replace( EXPRESSION, "$1");
}
所以,当我使用表达式.+B=(.+);.+
"运行它时我得到def_3%^123+-;C=123;"大概是因为它只是寻找';'的最后一个实例在字符串中,而不是在它遇到的第一个处停止.
so, when I run this using expression ".+B=(.+);.+
"
I get "def_3%^123+-;C=123;" presumably because it just looks for the LAST instance of ';' in the string, rather than stopping at the first one it comes to.
我试过使用 (?=) 来寻找第一个 ';'但它给了我相同的结果.
I've tried using (?=) in search of that first ';' but it gives me the same result.
我似乎找不到解释如何指定NEXT"标记而不是末尾标记的 regExp 参考.
I can't seem to find a regExp reference that explains how one can specify the "NEXT" token rather than the one at the end.
非常感谢任何和所有帮助.
any and all help greatly appreciated.
关于 SO 的类似问题:
Similar question on SO:
推荐答案
您正在使用贪婪模式,没有在其中指定 ?
.试试这个:
You're using a greedy pattern by not specifying the ?
in it. Try this:
".+B=(.+?);.+"
这篇关于需要正则表达式来查找两个标记之间的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!