简体   繁体   中英

Javascript match a string which start with a specific char from the set of chars and end with same char using Regular Expression

I need to achieve a particular task in javascript, in which my goal is to match the string which starts with a char from a specific set of characters like vowel and ends with the same character where the length of the string is greater than three.

so far I have done the following code that starts and ends with the same character but doesn't know how to specify it that the first char is from the specific set of character:

function regexVar() {

    var re = /(.).*\1/
    return re;
}

console.log("obcdo".test(s));

let suppose the specific set of chars is the vowel

(a, e, i, o, u)

in this case:

abcd ----> false

obcdo ----> true

ixyz ----> false

You need to use a character set to ensure the captured character is one of the ones you want, backreference the first captured group at the end of the pattern, not the third group (your pattern doesn't have 3 capture groups), use ^ and $ to anchor the pattern to the start and end of the string, and repeat with {2,} rather than * to make sure the whole string is at least 4 characters long:

/^([aeiou]).+\1$/

 const re = /^([aeiou]).{2,}\\1$/ console.log( re.test('abcd'), re.test('obcdo'), re.test('ixyz') );

You can use this pattern

/^([aeiou]).+\1$/i
  • ^ - Start of string
  • ([aeiou]) - Matches a,e,i,o,u any one of that. (group 1)
  • .+ - Match anything except new line.
  • \\1 - Match group 1
  • $ - End of string

 let startAndEnd = (str) =>{ return /^([aeiou]).+\\1$/i.test(str) } console.log(startAndEnd(`ixyz`)) console.log(startAndEnd(`abcd`)) console.log(startAndEnd(`obcdo`))

如果我们取一组元音,则以相同元音开头和结尾的单词的正则表达式为:

var re = /(\ba(\w+)a\b|\be(\w+)e\b|\bi(\w+)i\b|\bo(\w+)o\b|\bu(\w+)u\b)/g;
function regCheck(string){

    let re = new RegExp(/^(a|e|i|o|u).*\1$/g);
    return re.test(string);

}
regCheck('aewxyzae')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM