如何否定与 String replaceAll 方法一起使用的正则表达式模式?

How to negate a regex pattern to be used with String replaceAll method?

我希望得到一个只接受小写字母数字字符或 - 的字符串。如果字符串包含任何其他字符,则应将其替换为 -

我尝试了以下带有前瞻否定的正则表达式,但它在最后附加了一个额外的 -。我怎样才能解决这个问题?

public string sampleTest() {
  String name = "test-7657-hello.WOrld"
  return name.toLowerCase().replaceAll("(?![a-z0-9]([-a-z0-9]*[a-z0-9])?)", "-")
}

例如:应该把上例中的点替换成-

如果要用连字符替换 每个 字符,请使用 /[^a-z0-9-]/g:

abcd%$^.efg  -->  abcd----efg

为了替换 整个 无效子字符串,请使用 /[^a-z0-9-]+/g:

abcd%$^.efg  -->  abcd-efg

最后,我热烈建议您阅读正则表达式的/g(全局标志)属性。下次省你的力气了。

正则表达式([^a-z0-9-])

对于 Java [^a-z0-9-] 匹配列表中不存在的单个字符,因此可以将其替换为 -

详情:

  • [^] 匹配列表中不存在的单个字符 a-z 0-9 -
  • () 捕获组

输出:

test-7657-hello---rld

Regex demo