如何通过组合多个正则表达式来形成正则表达式

学习者

嗨,我有一个要求,我想根据它来形成一个正则表达式

  1. 如果它以正则表达式中的给定单词开头,则匹配整个单词
  2. 匹配整个双引号括起来的单词
  3. 如果单词以正则表达式中的给定单词开头,则在(..),[..],{..}中匹配单词-与(1)相似,除了方括号内

这是我形成正则表达式的方式

我想将它们结合起来,以便完美地工作

这是我尝试过的

var searchString = `virat "virat kohli" regarded ipl`;
var keywordList = searchString.split(/\s+/g);
var exactSearchList = searchString.match(/(?<=").*?(?=")/g);

var textDescription = `<pre>Virat Kohli (About this soundpronunciation (help·info); born 5 November 1988) is an Indian cricketer and the current captain of the India national team. A right-handed top-order batsman, Kohli is regarded as one of the best batsmen in the world.[3] He plays for Royal Challengers Bangalore in the Indian Premier League (IPL), and has been the team's captain since 2013. Since October 2017, he has been the top-ranked ODI batsman in the world and is currently 2nd in Test rankings with 886 points.[4][5] Among Indian batsmen, Kohli has the best ever Test rating (937 points), ODI rating (911 points) and T20I rating (897 points). 

  virat kohli is one of best performer in ipl

(virat )  (kohli)   

 kohli is good player virat virat kohli kohli

custom kohli virat virat kohli kohli virat "virat kohli"

 "virat kohli" "kohli virat" "virat"
"kohli"

Kohli captained India Under-19s to victory at the 2008 Under-19 World Cup in Malaysia. After a few months later, he made his ODI debut for India against Sri Lanka at the age of 19. Initially having played as a reserve batsman in the Indian team, he soon established himself as a regular in the ODI middle-order and was part of the squad that won the 2011 World Cup. He made his Test debut in 2011 and shrugged off the tag of "ODI specialist" by 2013 with Test hundreds in Australia and South Africa.[6] Having reached the number one spot in the ICC rankings for ODI batsmen for the first time in 2013,[7] Kohli also found success in the Twenty20 format, winning the Man of the Tournament twice at the ICC World Twenty20 (in 2014 and 2016).

Kohli was appointed the vice-captain of the ODI team in 2012 and handed over the Test captaincy following Mahendra Singh Dhoni's Test retirement in 2014. In early 2017, he became the limited-overs captain as well after Dhoni stepped down from the position. In ODIs, Kohli has the second highest number of centuries and the highest number of centuries in run-chases in the world. He holds the world record for being the fastest batsman to 8,000, 9,000, 10,000 and 11,000 runs in ODI cricket, reaching the milestones in 175, 194, 205 and 222 innings respectively.[8][9] [10][11]

Kohli has been the recipient of many awards such as the Sir Garfield Sobers Trophy (ICC Cricketer of the Year) in 2017 and 2018; ICC Test Player of the Year 2018; ICC ODI Player of the Year in 2012, 2017 and 2018 and Wisden Leading Cricketer in the World in 2016, 2017 and 2018.[12] He was given the Arjuna Award in 2013, the Padma Shri under the sports category in 2017[13] and the Rajiv Gandhi Khel Ratna, the highest sporting honour in India, in 2018.[14] Kohli is ranked as one of the world's most famous athletes by ESPN[15] and one of the most valuable athlete brands by Forbes.[16] In 2018, Time magazine named Kohli one of the 100 most influential people in the world.[17] In 2020, Kohli was ranked 66th in Forbes list of the top 100 highest paid athletes in the world for the year 2020 with estimated earnings of $26 million. Virat Kohli is the only cricketer to feature in Forbes.[18]</pre>`;


  var exactSearchListTemp = [];
  for(var i = 0; i < exactSearchList.length; i++){
     if(String(exactSearchList[i]).trim() != '')
      exactSearchListTemp.push(String(exactSearchList[i]).trim());
        }
        if(Array.isArray(exactSearchList) && exactSearchList.length) keywordList = keywordList.concat(exactSearchListTemp);
        var convertedRegex = keywordList.filter(function(el){
            return  el.replace(/\|/g,'');
        }).join('|');
        var pattern = new RegExp(`((?<=(^|\\s|^\\[?.*\\W]?|^\\()|^{?)(?:${convertedRegex}))\\S*`, 'ig');
        var highlightDesc = textDescription.replace(pattern, '<highlight>$&</highlight>');
       
$('#matchedContainer').html(highlightDesc);
 
#matchedContainer{
   border:1px solid #ccc;
   width:100%;
   height:400px;
}

highlight{
    font-weight: 400;
    background: #FF9800;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="matchedContainer"></div>

维克多·史翠比维

如果可以使用静态正则表达式,则可以使用

/(?<=[(["]\s*|\b)(virat(?: kohli)?|kohli)(?=\b|\s*[\])"])/gi

请参阅regex演示

细节

  • (?<=[(["]\s*|\b)-与后面的位置相匹配的正向后视,该位置紧接在之前(然后具有零个或多个空格字符或单词边界["
  • (virat(?: kohli)?|kohli)-与virat kohlivirat匹配的捕获组kohli
  • (?=\b|\s*[\])"])-匹配的位置的正向前查找紧接着用一个字边界或任何零个或多个空格,接着用])"

我的JavaScript尝试动态构建模式(假设要搜索的关键字在中提供searchString,其中双引号内的单词将作为单个关键字进行搜索):

var textDescription = "<pre>Virat Kohli (About this soundpronunciation (help·info); born 5 November 1988) is an Indian cricketer and the current captain of the India national team. A right-handed top-order batsman, Kohli is regarded as one of the best batsmen in the world.[3] He plays for Royal Challengers Bangalore in the Indian Premier League (IPL), and has been the team's captain since 2013. Since October 2017, he has been the top-ranked ODI batsman in the world and is currently 2nd in Test rankings with 886 points.[4][5] Among Indian batsmen, Kohli has the best ever Test rating (937 points), ODI rating (911 points) and T20I rating (897 points). \n\n  virat kohli is one of best performer in ipl\n\n(virat )  (kohli)   \n\n kohli is good player virat virat kohli kohli\n\ncustom kohli virat virat kohli kohli virat \"virat kohli\"\n\n \"virat kohli\" \"kohli virat\" \"virat\"\n\"kohli\"\n\nKohli captained India Under-19s to victory at the 2008 Under-19 World Cup in Malaysia. After a few months later, he made his ODI debut for India against Sri Lanka at the age of 19. Initially having played as a reserve batsman in the Indian team, he soon established himself as a regular in the ODI middle-order and was part of the squad that won the 2011 World Cup. He made his Test debut in 2011 and shrugged off the tag of \"ODI specialist\" by 2013 with Test hundreds in Australia and South Africa.[6] Having reached the number one spot in the ICC rankings for ODI batsmen for the first time in 2013,[7] Kohli also found success in the Twenty20 format, winning the Man of the Tournament twice at the ICC World Twenty20 (in 2014 and 2016).\n\nKohli was appointed the vice-captain of the ODI team in 2012 and handed over the Test captaincy following Mahendra Singh Dhoni's Test retirement in 2014. In early 2017, he became the limited-overs captain as well after Dhoni stepped down from the position. In ODIs, Kohli has the second highest number of centuries and the highest number of centuries in run-chases in the world. He holds the world record for being the fastest batsman to 8,000, 9,000, 10,000 and 11,000 runs in ODI cricket, reaching the milestones in 175, 194, 205 and 222 innings respectively.[8][9] [10][11]\n\nKohli has been the recipient of many awards such as the Sir Garfield Sobers Trophy (ICC Cricketer of the Year) in 2017 and 2018; ICC Test Player of the Year 2018; ICC ODI Player of the Year in 2012, 2017 and 2018 and Wisden Leading Cricketer in the World in 2016, 2017 and 2018.[12] He was given the Arjuna Award in 2013, the Padma Shri under the sports category in 2017[13] and the Rajiv Gandhi Khel Ratna, the highest sporting honour in India, in 2018.[14] Kohli is ranked as one of the world's most famous athletes by ESPN[15] and one of the most valuable athlete brands by Forbes.[16] In 2018, Time magazine named Kohli one of the 100 most influential people in the world.[17] In 2020, Kohli was ranked 66th in Forbes list of the top 100 highest paid athletes in the world for the year 2020 with estimated earnings of $26 million. Virat Kohli is the only cricketer to feature in Forbes.[18]</pre>";

const searchString = `virat "virat kohli" regarded ipl`;
const keywordList = searchString.match(/[^\s"]+|"[^"]+"/g).map(x => x.replace(/"/g, ''));
keywordList.sort((a, b) => b.length - a.length);
const pattern = new RegExp(String.raw`(?<=[(["]\s*|\b)(${keywordList.join("|")})(?=\b|\s*[\])"])`, 'ig');
const highlightDesc = textDescription.replace(pattern, '<highlight>$&</highlight>');
       
$('#matchedContainer').html(highlightDesc);
#matchedContainer{
   border:1px solid #ccc;
   width:100%;
   height:400px;
}

highlight{
    font-weight: 400;
    background: #FF9800;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="matchedContainer"></div>

在这里,模式是这样构建的:

const keywordList = searchString.match(/[^\s"]+|"[^"]+"/g).map(x => x.replace(/"/g, ''));
keywordList.sort((a, b) => b.length - a.length);
const pattern = new RegExp(String.raw`(?<=[(["]\s*|\b)(${keywordList.join("|")})(?=\b|\s*[\])"])`, 'ig');

代码的另一种变体,其中关键字列表是唯一单词的列表,这是"searchString空格中删除并拆分后的结果

const keywordList = [...new Set(searchString.replace(/"/g, '').split(/\s+/))];

var textDescription = "<pre>Virat Kohli (About this soundpronunciation (help·info); born 5 November 1988) is an Indian cricketer and the current captain of the India national team. A right-handed top-order batsman, Kohli is regarded as one of the best batsmen in the world.[3] He plays for Royal Challengers Bangalore in the Indian Premier League (IPL), and has been the team's captain since 2013. Since October 2017, he has been the top-ranked ODI batsman in the world and is currently 2nd in Test rankings with 886 points.[4][5] Among Indian batsmen, Kohli has the best ever Test rating (937 points), ODI rating (911 points) and T20I rating (897 points). \n\n  virat kohli is one of best performer in ipl\n\n(virat )  (kohli)   \n\n kohli is good player virat virat kohli kohli\n\ncustom kohli virat virat kohli kohli virat \"virat kohli\"\n\n \"virat kohli\" \"kohli virat\" \"virat\"\n\"kohli\"\n\nKohli captained India Under-19s to victory at the 2008 Under-19 World Cup in Malaysia. After a few months later, he made his ODI debut for India against Sri Lanka at the age of 19. Initially having played as a reserve batsman in the Indian team, he soon established himself as a regular in the ODI middle-order and was part of the squad that won the 2011 World Cup. He made his Test debut in 2011 and shrugged off the tag of \"ODI specialist\" by 2013 with Test hundreds in Australia and South Africa.[6] Having reached the number one spot in the ICC rankings for ODI batsmen for the first time in 2013,[7] Kohli also found success in the Twenty20 format, winning the Man of the Tournament twice at the ICC World Twenty20 (in 2014 and 2016).\n\nKohli was appointed the vice-captain of the ODI team in 2012 and handed over the Test captaincy following Mahendra Singh Dhoni's Test retirement in 2014. In early 2017, he became the limited-overs captain as well after Dhoni stepped down from the position. In ODIs, Kohli has the second highest number of centuries and the highest number of centuries in run-chases in the world. He holds the world record for being the fastest batsman to 8,000, 9,000, 10,000 and 11,000 runs in ODI cricket, reaching the milestones in 175, 194, 205 and 222 innings respectively.[8][9] [10][11]\n\nKohli has been the recipient of many awards such as the Sir Garfield Sobers Trophy (ICC Cricketer of the Year) in 2017 and 2018; ICC Test Player of the Year 2018; ICC ODI Player of the Year in 2012, 2017 and 2018 and Wisden Leading Cricketer in the World in 2016, 2017 and 2018.[12] He was given the Arjuna Award in 2013, the Padma Shri under the sports category in 2017[13] and the Rajiv Gandhi Khel Ratna, the highest sporting honour in India, in 2018.[14] Kohli is ranked as one of the world's most famous athletes by ESPN[15] and one of the most valuable athlete brands by Forbes.[16] In 2018, Time magazine named Kohli one of the 100 most influential people in the world.[17] In 2020, Kohli was ranked 66th in Forbes list of the top 100 highest paid athletes in the world for the year 2020 with estimated earnings of $26 million. Virat Kohli is the only cricketer to feature in Forbes.[18]</pre>";

const searchString = `virat "virat kohli" regarded ipl`;
const keywordList = [...new Set(searchString.replace(/"/g, '').split(/\s+/))];
keywordList.sort((a, b) => b.length - a.length);
const pattern = new RegExp(String.raw`(?<=[(["]\s*|\b)(${keywordList.join("|")})(?=\b|\s*[\])"])`, 'ig');
const highlightDesc = textDescription.replace(pattern, '<highlight>$&</highlight>');
       
$('#matchedContainer').html(highlightDesc);
#matchedContainer{
   border:1px solid #ccc;
   width:100%;
   height:400px;
}

highlight{
    font-weight: 400;
    background: #FF9800;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="matchedContainer"></div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章