简体   繁体   English

正则表达式以匹配以点开头和结尾的字符串

[英]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. 例如,在文本中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. 有两种方法1)如果要查找以点开头和结尾的字符串。

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

2) if you want to find string between dots. 2)如果要在点之间查找字符串。

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

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+\\.$ 例如,仅匹配单词字符^\\.+\\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); } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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