简体   繁体   中英

How can I represent this regex in java?

I have this regex: [^\\w\\s+]

Regex101 link.

And I'm trying to use it in java to replace the matched characters. I realized I need to escape the brackets and the slashes but it's still not working as expected.

This is what I have so far:

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

Short version: Don't escape brackets.

The wonderful online tool https://regex101.com/ helps you to get your regular expressions correct and running. If you insert your expression and use the code generator (sidebar left), it produces the following for Java (along with some code for using the regex):

final String regex = "[^\\w\\s+]";

You Should Use Regex Like That

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+]","");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM