Javascript解决方案,用于查找前缀和后缀之间的每个子字符串

时间:2017-05-03 08:36:36

标签: javascript node.js regex

我有一个以下格式的字符串,

  

Hello this #result1# is a sample #result2# string with a lot of # and #result3# i need to find all the values between #

我需要基于javascript或nodejs的解决方案,只能返回['result1' , 'result2' , 'result3']

规则:

  1. 预期结果之间没有空格
  2. 预期结果之间没有#
  3. 应排除['result1# is a sample #result2# string with a lot of ' , 'result1# is a sample ']
  4. 等结果

4 个答案:

答案 0 :(得分:1)



var str = 'Hello this #result1# is a sample #result2# string with a lot of # and  #result3# i need to find all the values between #';
console.log(str.match(/#[^#\s]+#/g));




<强>解释

/        : regex delimiter
 #       : # character
 [^#\s]+ : 1 or more character that is NOT # or space
 #       : # character
/g       : regex delimiter and global flag

答案 1 :(得分:0)

以下代码段应该有效:

&#13;
&#13;
let str = "Hello this #result1# is a sample #result2# string with a lot of # and  #result3# i need to find all the values between #";
let identifier = '#';

function getSubstrings(str, identifier) {
    let results = [];
    let splittedItems = str.split(identifier);
    splittedItems.forEach(
        function(item) {
            if (item.length > 1 && item.indexOf(' ') === -1) {
                results.push(item);
            }
        }
    );
    return results;
}
document.write(getSubstrings(str, identifier));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

/#(.*?)#

在行动here

中查看

答案 3 :(得分:0)

您的问题可能有许多特殊情况,如果没有关于您尝试过的内容以及失败的详细信息,很难给出明确的答案。 您可以尝试从以下开始:

var input = 'Hello this #result1# is a sample #result2# string with a lot of # and  #result3# i need to find all the values between #';
output = input.match(/#[A-Za-z0-9]+#/g);
console.log(output); //["#result1#", "#result2#", "#result3#"]

[A-Za-z0-9]匹配任何大写字母(A-Z),小写字母(a-z)和数字(0-9

+表示前面的模式至少应出现一次

g表示全局,因此匹配字符串

中模式的所有出现

它应该让你去。