[英]Specific pattern matching in Regex in Javascript
I want to use regex to match the string of the following format : ( #sometext#
)我想使用正则表达式来匹配以下格式的字符串:(
#sometext#
)
In the sense ,whatever is there between ( #
and #
) only should be matched.从某种意义上说,(
#
和#
)之间的任何内容都应该匹配。 So, the text:所以,正文:
var s = "hello(%npm%)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello(%npm%)hi
And和
var s = "hello(#npm#)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello
alert(res[1]);
o/p : (#npm#);
But the thing is , the regex /(\\([^()]*\\))/
is matching everything between ()
rather than extracting the string including (# .. #)
like:但问题是,正则表达式
/(\\([^()]*\\))/
匹配()
之间的所有内容,而不是提取包括(# .. #)
的字符串,例如:
hello
(#npm#)
hi
By going in your way of fetching content, try this:通过采用您获取内容的方式,试试这个:
var s = "hello(%npm%)hi"; var res = s.split(/\\(%(.*?)%\\)/); alert(res[1]); //o/p: hello(%npm%)hi var s = "hello(#npm#)hi"; var res = s.split(/(\\(#.*?#\\))/); console.log(res); //hello, (#npm#), hi
From your comment, updated the second portion, you get your segments in res array:根据您的评论,更新了第二部分,您将在 res 数组中获取您的段:
[
"hello",
"(#npm#)",
"hi"
]
The following pattern is going to give the required output:以下模式将提供所需的输出:
var s = "hello(#&yu()#$@8#)hi";
var res = s.split(/(\(#.*#\))/);
console.log(res);
"." “。” matches everything between (# and #)
匹配 (# 和 #) 之间的所有内容
It depends if you have multiple matches per string.这取决于每个字符串是否有多个匹配项。
// like this if there is only 1 match per text var text = "some text #goes#"; var matches = text.match(/#([^#]+)#/); console.log(matches[1]); // like this if there is multiple matches per text var text2 = "some text #goes# and #here# more"; var matches = text2.match(/#[^#]+#/g).map(function (e){ // strip the extra #'s return e.match(/#([^#]+)#/)[1]; }); console.log(matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.