Page 1 of 1

need help to create a regular expression for this

Posted: Sat Jul 17, 2010 4:45 pm
by mgwalk
here is my string multiple lines
368.7,633.2 368.7,633.2 369.2,633.8 369.4,634.2 369.9,634.2 370,634.2 \r\n
370.6,634.3 371,634 371.3,633.7 371.6,633.9 372.2,634.5

I need to create a regular expression to this string basically
remove the decimals
replace the spaces with a comma
and remove the space + carriage return + line feed

368,633,368,633,369,633,369,634,369,634,370,634,370,634,371,634,371,633,371,633,372,634

Re: need help to create a regular expression for this

Posted: Sat Jul 17, 2010 4:58 pm
by AbraCadaver
Is there always going to be a space before the \r\n?

Re: need help to create a regular expression for this

Posted: Sat Jul 17, 2010 5:03 pm
by mgwalk
Yes there is always a space before the \r\n

Re: need help to create a regular expression for this

Posted: Sat Jul 17, 2010 5:22 pm
by AbraCadaver
Dunno why I asked that, doesn't matter. :( Just a little regex: :)

Code: Select all

$new_string = implode(',', array_map('intval', explode(',', preg_replace('/[\s]+/', ',', $string))));

Re: need help to create a regular expression for this

Posted: Sat Jul 17, 2010 6:26 pm
by mgwalk
Thanks for the example. How about just regular expression no php?

Re: need help to create a regular expression for this

Posted: Sat Jul 17, 2010 6:49 pm
by AbraCadaver
Ahhh sorry, I didn't pay attention to the forum this was in. Maybe a regex guru will answer, but for me, I can't see it without two regex replaces. This is PHP, but the patterns should be valid for whatever language you're using:

Code: Select all

$new_string = preg_replace('/\.[\d]+/', '', preg_replace('/[\s]+/', ',', $string));

Re: need help to create a regular expression for this

Posted: Mon Jul 19, 2010 11:52 pm
by ridgerunner
remove the decimals:

Code: Select all

$str = preg_replace('/\b(\d+)\.\d+\b/', '$1', $str);
replace the spaces with a comma and remove the space + carriage return + line feed

Code: Select all

$str = preg_replace('/[ \r\n]+/', ',', $str);
Hope this helps :)