正则表达式,无重复的特殊字符

时间:2020-04-06 06:11:45

标签: javascript regex angular

我的要求是不得重复特殊字符

我目前有

const reg=(/[^.*a-zA-Z0-9.,\s]*/g, '')

我想允许

sometext . something

我不想允许

sometext,, something . some. some,

1 个答案:

答案 0 :(得分:1)

如果您不想在完整的字符串中重复特殊字符。您可以使用matchSet

let nonRepeated = (str) => {
  let match = str.match(/[.,]/g) || []
  let setMatch = new Set(match)
  return match.length != setMatch.size
}

console.log(nonRepeated('sometext . something'))
console.log(nonRepeated('sometext,, something . some. some,'))

如果您不想连续使用特殊字符,则可以使用类似的方法

let nonRepeated = (str) =>  !/([,.])(?=\1)/.test(str)

console.log(nonRepeated('sometext . something'))
console.log(nonRepeated('sometext,, something . some. some,'))