nsuspect
nsuspect

Reputation: 59

Regex to match string in a sentence

I am trying to find a strictly declared string in a sentence, the thread says:

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.

I've gotten this far:

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())

The result should be:

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

Upvotes: 2

Views: 1822

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

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

function findTheNumber(words){
    console.log( words.replace(/\b(t[e]n)\b|[^.]/g, (x,y) => y ?? " ") )
}
findTheNumber(text)

The \b(t[e]n)\b is basically ten whole word searching pattern.

The \b(t[e]n)\b|[^.] regex will match and capture ten into Group 1 and will match any char but . (as you need to keep it at the end). If Group 1 matches, it is kept (ten remains in the output), else the char matched is replaced with a space.

Depending on what chars you want to keep, you may adjust the [^.] pattern. For example, if you want to keep all non-word chars, you may use \w.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

You could try a regex replacement approach, with the help of a callback function:

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);

The above logic matches every word in the input sentence, and then selectively replaces every word which is not ten with an equal number of spaces.

Upvotes: 2

Related Questions