[英]Regex check if a character only occurs at the end of a string
我正在嘗試匹配一個字符串,該字符串僅在第一次出現目標字符之后的所有字符也是目標字符時才有效。
為了更好地理解結構,例如我們的目標字符是.
. 字符串分為兩部分。 匹配字符串具有以下結構:
讓我們看一些例子:
""
// 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)
我首先通過檢查第一次出現的索引,然后計算出現的次數,與字符串的長度進行比較以檢查結尾之間是否還有其他字符來解決問題,從而解決了問題,但是看起來不太好,我認為這不是解決問題的最有效方法。
它看起來像這樣:
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;
}
然后我在研究正則表達式的方法來解決這個問題,但我只找到了檢查出現的方法,出現的次數,如果字符串以結尾(甚至n次,但忽略其他字符之間是否出現),但無法計算匹配上述測試的方法。
正則表達式^[^.]*\.*$
應該可以工作。 它可以接受任何 none .
字符 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.'))
英語:如果它是零個或多個非點字符后跟零個或多個點字符,則匹配:
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
>
^[\.]*$
\.$
將它們交替放在一起,你會在最后得到點或者根本不會
(\.$)|(^[\.]*$)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.