簡體   English   中英

Javascript中正則表達式中的特定模式匹配

[英]Specific pattern matching in Regex in Javascript

我想使用正則表達式來匹配以下格式的字符串:( #sometext#

從某種意義上說,( ## )之間的任何內容都應該匹配。 所以,正文:

var s = "hello(%npm%)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello(%npm%)hi

var s = "hello(#npm#)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello
alert(res[1]);
o/p : (#npm#);

但問題是,正則表達式/(\\([^()]*\\))/匹配()之間的所有內容,而不是提取包括(# .. #)的字符串,例如:

hello
(#npm#)
hi

通過采用您獲取內容的方式,試試這個:

 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

根據您的評論,更新了第二部分,您將在 res 數組中獲取您的段:

[
  "hello",
  "(#npm#)",
  "hi"
]

以下模式將提供所需的輸出:

var s = "hello(#&yu()#$@8#)hi";
var res = s.split(/(\(#.*#\))/);
console.log(res);

“。” 匹配 (# 和 #) 之間的所有內容

這取決於每個字符串是否有多個匹配項。

 // 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM