javascript - 正则表达式匹配句子中的字符串

标签 javascript regex

我试图在句子中找到严格声明的字符串,线程说:

Find the position of the string "ten" within a sentence, without using the exact string directly (this can be avoided in many ways using just a bit of RegEx). Print as many spaces as there were characters in the original sentence before the aforementioned string appeared, and then the string itself in lowercase.

我已经走到这一步了:

let words = 'A ton of tunas weighs more than ten kilograms.'

function findTheNumber(){

         let regex=/t[a-z]*en/gi;
         let output = words.match(regex)
         console.log(words)
         console.log(output) 
}

console.log(findTheNumber())

结果应该是:

input  = A ton of tunas weighs more than ten kilograms.
output =                                 ten(ENTER)           

最佳答案

您可以在回调函数的帮助下尝试正则表达式替换方法:

var input = "A ton of tunas weighs more than ten kilograms.";
var output = input.replace(/\w+/g, function(match, contents, offset, input_string)
{
    if (!match.match(/^[t][e][n]$/)) {
        return match.replace(/\w/g, " ");
    }
    else {
        return match;
    }
});
console.log(input);
console.log(output);

上述逻辑匹配输入句子中的每个单词,然后有选择地将每个不是 10 的单词替换为相同数量的空格。

关于javascript - 正则表达式匹配句子中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69166064/

相关文章:

javascript - 覆盖可点击的div

javascript - Typescript (Javascript) 中奇怪的类属性分配 : '?='

java - 字符串分隔的正则表达式

javascript - 防止链接按钮回发 OnClientClick 不起作用。为什么?

javascript - 针对资源的 AngularJS 自定义验证

javascript - 为什么我的代码抛出 "Cannot read property ' ParentNode' of undefined”?

java - 如何检查特定模式是否在某些字符之前?

javascript - 了解正则表达式?

javascript - 句子中每个单词的匹配模式

python - 如何正确拆分此字符串列表?