PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to remove all non-alphanumeric characters from a string expect decimal point in Java

 August 07, 2022     decimal, java, regex     No comments   

Issue

Having this String with decimal point, I would like to remove all non alphaNumeric expect the decimal point.

 String toPharse = "the. book - cost 7.55 dollars.";

 String newPharse =  toPharse.replaceAll("[^A-Za-zd.0-9 ]", " ").replaceAll("\\s+", " ");

Currently I get "the. book cost 7.55 dollars.";

However I would like to return "the book cost 7.55 dollars";


Solution

You can use:

String toPharse = "the. book - cost 7.55 dollars.";
toPhrase = toPharse
   .replaceAll("(?<!\\d)\\.(?!\\d)|[^a-zA-Z\\d. ]+", "")
   .replaceAll("\\h{2,}", " ");

//=> "the book cost 7.55 dollars"

RegEx Demo

RegEx Details:

  • (?<!\\d): Previous character is not a digit
  • \\.: Match a dot
  • (?!\\d): Next character is not a digit
  • |: OR
  • [^a-zA-Z\\d. ]+: Match 1+ of non-alphanumeric characters that are not space or dot
  • .replaceAll("\\h{2,}", " "): is for replacing 2+ whitespaces with a single space


Answered By - anubhava
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing