Удаление спецсимволов из строки java

удалить весь специальный символ из строки java

Я хотел знать, как я могу сделать, чтобы полностью исключить ВСЕ специальные символы из строки. Другими словами, я оставил бы только слова, таким образом, исключив любые другие символы как + -òç @èé и т.д.

myString = Normalizer.normalize(myString, Normalizer.Form.NFD).replaceAll("[^\\p]", ""); 

Но некоторые символы speacials все еще остаются.

Замените класс regex \p на более строгий набор, содержащий только символы, которые вы разрешаете. Например,

myString = Normalizer.normalize(myString, Normalizer.Form.NFD).replaceAll("[^a-zA-Z]", ""); 

сначала разложит акцентированные символы, такие как é на две части e + combining ´ (нормальная форма D), а затем регулярное выражение удалит любой символ, который не является ASCII a..z или A..Z.

Кодировка по умолчанию – unicode (utf-8) в java. В приведенном ниже коде используется представление символа unicode символа и проверяется, является ли юникод символа характерным символом; Решение, приведенное ниже, относится к сложности времени = O (n);

public class RemoveSpecialCharacters < /** * @param args the command line arguments */ private static boolean isSpecialCharacter(int b) < if((b>=32 && b=58 && b<=64)||(b>=91 && b<=96) ||(b>=123 && b<=126)||b>126) return true; return false; > public static String removeSpecialCharacters(String a) < StringBuffer s=new StringBuffer(a); int lenvar=s.length(); String myString=""; for(int i=0;i> return myString; > public static void main(String[] args) < System.out.println(removeSpecialCharacters("fleCKHE)_+_+")); >> 

Источник

Удаление спецсимволов из строки java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Удалить все небуквенно-цифровые символы из строки в Java

В этом посте будет обсуждаться, как удалить все символы, отличные от буквенно-цифровых, из строки в Java.

1. Использование String.replaceAll() метод

Распространенным решением для удаления всех неалфавитно-цифровых символов из строки являются регулярные выражения. Идея состоит в том, чтобы использовать регулярное выражение [^A-Za-z0-9] чтобы сохранить только буквенно-цифровые символы в строке.

результат:

ABCDE1

Вы также можете использовать [^\w] регулярное выражение, которое эквивалентно [^a-zA-Z_0-9] . Он заменит символы, которых нет в диапазоне символов. A-Z , a-z , 0-9 , _ . В качестве альтернативы вы можете использовать класс символов \W который непосредственно соответствует любому символу, не являющемуся словом, т. е. [a-zA-Z_0-9] .

результат:

ABCD_E1

Обратите внимание, что это решение сохраняет символ подчеркивания. Если вам также нужно удалить подчеркивание, вы можете использовать регулярное выражение [\W]|_ . В качестве альтернативы вы можете использовать класс символов POSIX \p , который соответствует любому буквенно-цифровому символу [A-Za-z0-9] . Это эквивалентно [\p\p] .

результат:

ABCDE1

2. Использование Guava

Если вы используете библиотеку Guava в своем проекте, вы можете использовать ее javaLetterOrDigit() метод из CharMatcher класс, чтобы определить, является ли символ буквой или цифрой. Вы можете удалить или сохранить все совпадающие символы, возвращаемые javaLetterOrDigit() метод с использованием removeFrom() а также retainFrom() метод соответственно. Это показано ниже:

Источник

How To Remove a Character from a String in Java

How To Remove a Character from a String in Java

In this article, you’ll learn a few different ways to remove a character from a String object in Java. Although the String class doesn’t have a remove() method, you can use variations of the replace() method and the substring() method to remove characters from strings.

Note: String objects are immutable, which means that they can’t be changed after they’re created. All of the String class methods described in this article return a new String object and do not change the original object. The type of string you use depends on the requirements of your program. Learn more about other types of string classes and why strings are immutable in Java.

The String class has the following methods that you can use to replace or remove characters:

  • replace(char oldChar, char newChar) : Returns a new String object that replaces all of the occurrences of oldChar in the given string with newChar . You can also use the replace() method, in the format replace(CharSequence target, CharSequence replacement) , to return a new String object that replaces a substring in the given string.
  • replaceFirst(String regex, String replacement) : Returns a new String object that replaces the first substring that matches the regular expression in the given string with the replacement.
  • replaceAll(String regex, String replacement) : Returns a new String object that replaces each substring that matches the regular expression in the given string with the replacement.
  • substring(int start, int end) : Returns a new String object that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end minus 1.

Notice that the first argument for the replaceAll() and replaceFirst() methods is a regular expression. You can use a regular expression to remove a pattern from a string.

Note: You need to use double quotes to indicate literal string values when you use the replace() methods. If you use single quotes, then the JRE assumes you’re indicating a character constant and you’ll get an error when you compile the program.

Remove a Character from a String in Java

You can remove all instances of a character from a string in Java by using the replace() method to replace the character with an empty string. The following example code removes all of the occurrences of lowercase “ a ” from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replace("a", ""); 

Remove Spaces from a String in Java

You can remove spaces from a string in Java by using the replace() method to replace the spaces with an empty string. The following example code removes all of the spaces from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replace(" ", ""); 

Remove a Substring from a String in Java

You can remove only the first occurrence of a character or substring from a string in Java by using the replaceFirst() method to replace the character or substring with an empty string. The following example code removes the first occurrence of “ ab ” from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replaceFirst("ab", ""); 

Remove all the Lowercase Letters from a String in Java

You can use a regular expression to remove characters that match a given pattern from a string in Java by using the replace.All() method to replace the characters with an empty string. The following example code removes all of the lowercase letters from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replaceAll("([a-z])", ""); 

Remove the Last Character from a String in Java

There is no specific method to replace or remove the last character from a string, but you can use the String substring() method to truncate the string. The following example code removes the last character from the given string:

String str = "abc ABC 123 abc"; String strNew = str.substring(0, str.length()-1); 

Try it out

The following example file defines a class that includes all of the method examples provided in this article, and prints out the results after invoking each method on the given string. You can use this example code to try it out yourself on different strings using different matching patterns and replacement values.

If you have Java installed, you can create a new file called JavaStringRemove.java and add the following code to the file:

 public class JavaStringRemove  public static void main(String[] args)  String str = "abc ABC 123 abc"; // Remove a character from a string in Java System.out.println("String after removing all the 'a's = "+str.replace("a", "")); // Remove spaces from a string in Java System.out.println("String after removing all the spaces = "+str.replace(" ", "")); // Remove a substring from a string in Java System.out.println("String after removing the first 'ab' substring = "+str.replaceFirst("ab", "")); // Remove all the lowercase letters from a string in Java System.out.println("String after removing all the lowercase letters = "+str.replaceAll("([a-z])", "")); // Remove the last character from a string in Java System.out.println("String after removing the last character = "+str.substring(0, str.length()-1)); > > 

Compile and run the program:

You get the following output:

Output
String after removing all the 'a's = bc ABC 123 bc String after removing all the spaces = abcABC123abc String after removing the first 'ab' substring = c ABC 123 abc String after removing all the lowercase letters = ABC 123 String after removing the last character = abc ABC 123 ab

Each method in the JavaStringRemove example class operates on the given string. The output shows that the characters specified in each method have been removed from the string.

Conclusion

In this article you learned various ways to remove characters from strings in Java using methods from the String class, including replace() , replaceAll() , replaceFirst() , and substring() . Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Удалить все специальные символы из строки Java

Я хотел знать, как я могу сделать, чтобы полностью исключить ВСЕ специальные символы из строки. Другими словами, я бы оставил только слова, исключив, таким образом, любые другие символы, такие как «+» и т. Д.

myString = Normalizer.normalize(myString, Normalizer.Form.NFD).replaceAll("[^\\p]", ""); 

Но некоторые специальные персонажи все еще остаются.

2 ответа

Заменить \p Класс регулярных выражений с более строгим набором, который содержит только разрешенные вами символы. Например,

myString = Normalizer.normalize(myString, Normalizer.Form.NFD).replaceAll("[^a-zA-Z]", ""); 

будет сначала разлагать акцентированные символы как é на две части e + combining ´ (нормальная форма D), а затем регулярное выражение удалит любой символ, который не является ASCII a..z или A..Z.

Кодировка по умолчанию — это Unicode (UTF-8) в Java. В приведенном ниже коде используется Unicode-представление символа и проверяется, является ли Unicode символа специальным символом; Решение, приведенное ниже, имеет временную сложность = O(n);

public class RemoveSpecialCharacters < /** * @param args the command line arguments */ private static boolean isSpecialCharacter(int b) < if((b>=32 && b=58 && b<=64)||(b>=91 && b<=96) ||(b>=123 && b<=126)||b>126) return true; return false; > public static String removeSpecialCharacters(String a) < StringBuffer s=new StringBuffer(a); int lenvar=s.length(); String myString=""; for(int i=0;i> return myString; > public static void main(String[] args) < System.out.println(removeSpecialCharacters("fleCKHE)_+_+")); >> 

Источник

Читайте также:  Классические сервера css v34
Оцените статью