Can you help with regular expressions in Java?

I have a bunch of lines that may not have random characters and numbers in them. Here are some examples:

contains(reserved[j])){ close(); i++){ letters[20]=word 

I want to find any character that is NOT a letter and replace it with a space, so the above examples look like this:

 contains reserved j close i letters word 

What is the best way to do this?

+4
source share
4 answers

It depends on what you mean by “not a letter,” but if you mean that the letters are az or AZ, try this:

 s = s.replaceAll("[^a-zA-Z]", " "); 

If you want to collapse several characters into one space, add a plus to the end of the regular expression.

 s = s.replaceAll("[^a-zA-Z]+", " "); 
+3
source
 yourInputString = yourInputString.replaceAll("[^\\p{Alpha}]", " "); 

^ stands for "all characters except"

\p{Alpha} denotes all alphabetic characters

See http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html for details

+2
source

I want to find any character that is NOT a letter

This will be [^\p{Alpha}]+ . [] indicates a group. \p{Alpha} matches any alphabetic character (in both upper and lower case, it basically matches \p{Upper}\p{Lower} and a-zA-Z . The inner group ^ inverts matches. + indicates one or many matches in a sequence.

and replace it with a space

It will be " " .

Summarized:

 string = string.replaceAll("[^\\p{Alpha}]+", " "); 

Also see java.util.regex.Pattern javadoc for a brief overview of the available templates. You can learn more about regular expressions at the large site http://regular-expression.info .

+1
source

Use regexp / [^ a-zA-Z] /, which means not in az / AZ characters

In ruby, I would do:

 "contains(reserved[j]))".gsub(/[^a-zA-Z]/, " ") => "contains reserved j " 

In Java, there should be something like:

 import java.util.regex.*; ... String inputStr = "contains(reserved[j])){"; String patternStr = "[^a-zA-Z]"; String replacementStr = " "; // Compile regular expression Pattern pattern = Pattern.compile(patternStr); // Replace all occurrences of pattern in input Matcher matcher = pattern.matcher(inputStr); String output = matcher.replaceAll(replacementStr); 
0
source

Source: https://habr.com/ru/post/1308614/


All Articles