如何在Java中表示此正则表达式?

时间:2019-01-28 14:31:08

标签: java regex

我有这个正则表达式:[^\w\s+]

Regex101 link.

我正在尝试在Java中使用它来替换匹配的字符。我意识到我需要转义括号和斜杠,但仍无法按预期工作。

这是我到目前为止所拥有的:

content = content.replaceAll("\\[^\\w\\s+\\]", "");

2 个答案:

答案 0 :(得分:3)

简短版本:请勿逃脱括号。

出色的在线工具https://regex101.com/可帮助您正确设置和运行正则表达式。如果您插入表达式并使用代码生成器(左侧边栏),它将为Java生成以下内容(以及一些使用正则表达式的代码):

foo

答案 1 :(得分:0)

您应该使用正则表达式

String text = "RegExr was created by[...], and is proudly hosted by Media Temple.Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & Javascript flavors of RegEx are supported.The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns.Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.";
text=text.replaceAll("[^\\w\\s+]","");