Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular expressions to insert space into a camel case string

I am using the following regular expression to insert spaces into a camel-case string

var regex = /([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g;

Example usage

var str = "CSVFilesAreCoolButTXTRules";
str = str.replace( regex, '$1$4 $2$3$5' );
// "CSV Files Are Cool But TXT Rules"

This works fine, but I also want to put spaces before and after any numbers in the string, though I don't want space inserted between individual digits, and if a number is preceded by a $ then the space should go before it, and not the number.

I also want to remove any characters apart from numbers, letters, the $ sign and a dot . within a number.

For example,

MRRPLowPriceUSD$10.10HighPriceUSD$1998.59595CommentsNoChangeReportedNTPL1001KSE-100INDEX

should become

MRRP Low Price USD $10.10 High Price USD $1998.59595 Comments No Change Reported NTPL 1001 KSE 100 INDEX

Note that the - was removed.

Any assistance would be appreciated.

Related: putting-space-in-camel-case-string-using-regular-expression.

like image 594
KMX Avatar asked Mar 12 '13 23:03

KMX


People also ask

Does camel case have spaces?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.

How do you find a space in a string in regex?

To find whitespaces in a string, there are three common regexes in Java: \s: It represents a single white space. \s+: It indicates multiple white spaces. \u0020: It is the Unicode of the white space used as a regex to find whitespace in a text.

How do you make a camelCase string in typescript?

The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively. Example 1: This example uses reduce , toLowerCase() and toUpperCase() methods to convert a string into camelCase.


1 Answers

Try this regex and replace using positive look-ahead:

var regex = /([^A-Za-z0-9\.\$])|([A-Z])(?=[A-Z][a-z])|([^\-\$\.0-9])(?=\$?[0-9]+(?:\.[0-9]+)?)|([0-9])(?=[^\.0-9])|([a-z])(?=[A-Z])/g;
var str = "CSVFilesAreCool123B--utTXTFoo12T&XTRules$123.99BAz";
str = str.replace(regex, '$2$3$4$5 ');
// CSV Files Are Cool 123 B ut TXT Foo 12 T XT Rules $123.99 B Az

(RegExr)

like image 194
speakr Avatar answered Sep 30 '22 18:09

speakr