简体   繁体   中英

Regex to match a string that starts and ends with a dot

I need a regex to match a string that starts with a dot and ends with dot.

My try:

let sr = /^\.+\.$/g.test('.some.')
console.log(sr)

What am I missing?

您缺少一个点:

let sr = /^\..+\.$/g.test('.some.')

It isn't entirely clear what your criteria are for making a match, but the following is one interpretation:

 let sr = /^\\.[^.]+\\.$/g.test('.some.'); console.log(sr); 

If you can provide logic for how we might know that a sequence beginning with a dot gets invalidated, then the pattern can be updated. For example, in the text Mr. Bean goes to Hollywood. , you probably would not want to match between the two dots. In this case, we could modify the code to something like this:

let sr = /^\.[A-Za-z0-9]]+\.$/g.test('.some.');
console.log(sr);

This would allow only letters and numbers in between two candidate dots.

Till what i understand from your question. there are two way 1) If you want to find string which start and end with dot.

[\\.].*?[\\.]

2) if you want to find string between dots.

(?<=\\.)(.*?)(?=\\.)

Your regex ^\\.+\\.$ matches one or more times a dot followed by a dot at the end of the string. Between matching the first and the last dot, you could add what you want to match and use the quantifier + to repeat that one or more times instead of the first dot. For example matching only word characters ^\\.+\\w+\\.$

A non regex approach checking the first and the last character of a string might be:

 const strings = [ '.some test.', '.', '..', '.some.', 'some' ]; strings.forEach((str) => { if (str.length > 2 && str[0] === '.' && str[str.length - 1] === '.') { console.log("Matched: " + str); } }); 

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