Regex检查一个字符是否只出现在字符串的末尾



我正在尝试匹配一个字符串,该字符串仅在所有字符第一次出现目标字符之后有效,也是目标字符。

为了更好地理解结构,例如我们的目标字符是.。琴弦分为两部分。匹配的字符串具有以下结构:

  1. 子字符串,目标字符
  2. 子字符串,不包含除以外的其他字符目标字符

让我们来看看一些例子:

""
// true - 1: "" doesn't contain target - 2: "" doesn't contain not target
"2"
// true - 1: "2" doesn't contain target - 2: "" doesn't contain not target
"."
// true - 1: "" doesn't contain target - 2: "." doesn't contain not target (only target)
"2.."
// true - 1: "2" doesn't contain target - 2: ".." doesn't contain not target (only target)
"...."
// true - 1: "" doesn't contain target - 2: "...." doesn't contain not target (only target)
"..2"
// false - 1: "..2" contains target - 2: "" doesn't contain not target
"2.2"
// false - 1: "2.2" contains target - 2: "" doesn't contain not target
"2.2."
// false - 1: "2.2" contains target - 2: "." doesn't contain not target (only target)

我首先用字符串方法(JS)来解决问题,通过检查第一次出现的索引,然后计算出现的次数,比较字符串的长度来检查结束之间是否有任何其他字符,这解决了问题,但看起来不太好,我认为这不是解决问题的最有效方法。

它看起来像这样:

const validate = (string, targetChar) => {
const firstTargetIndex = string.indexOf(targetChar);
if (firstTargetIndex === -1) return true; //no chance of not target following a target
const substringAfterFirstTarget = string.substr(firstTargetIndex);
const numberOfTargets = substringAfterFirstTarget.split(targetChar).length - 1;
return substringAfterFirstTarget.length === numberOfTargets;
}

然后我正在研究regex方法来解决问题,但我只找到了检查出现次数,出现次数,如果字符串以(甚至n次,但忽略其他字符之间是否有出现)结束的方法,但无法找到匹配上述测试的方法。

正则表达式^[^.]*.*$应该工作。它可以接受任何无.字符0次或多次([^.]*),然后可以后跟任意数量的.(.*)

const regex = /^[^.]*.*$/gm;
const str = ['','2','.','2..','....','..2','2.2','2.2.'];
console.log(str.map(s=>s.match(regex)?'true':'false'))
// example from comments does return false
console.log(regex.test('..2.'))

  1. 点不在字符串中的情况:^[.]*$
  2. 点结束字符串的大小写:.$

将它们交替放在一起,你可以在末尾得到点或者根本没有

(.$)|(^[.]*$)

(英文):在0个或多个非点字符后面跟着0个或多个点字符时匹配:

Mac_3.2.57$cat test.txt | egrep "^[^.]*.*$"
2
.
2..
....
x
Mac_3.2.57$cat test.txt
2
.
2..
....
..2
2.2
2.2.
x
Mac_3.2.57$

PS前面的答案不适合我:

> const str = ['','2','.','2..','....','..2','2.2','2.2.'];
Uncaught SyntaxError: Identifier 'str' has already been declared
> console.log(str.map(s=>s.match(regex)?'true':'false'))
[
'true',  'true',
'true',  'true',
'true',  'false',
'false', 'false'
]
undefined
> const str = ['','2','.','2..','..2.','..2','2.2','2.2.'];
Uncaught SyntaxError: Identifier 'str' has already been declared
> console.log(str.map(s=>s.match(regex)?'true':'false'))
[
'true',  'true',
'true',  'true',
'true',  'false',
'false', 'false'
]
undefined
> 

相关内容

  • 没有找到相关文章

最新更新