replace spaces

  • Thread starter Thread starter RobcPettit
  • Start date Start date
R

RobcPettit

Hi, given the string '1(10) 00069- rob c pettit 54' Id like to know if
its possile to replaces spaces with - only when preceded with a letter
and followed with a letter. Giving '1(10) 00069- rob-c-pettit 54'
Regards Robert
 
Hi, given the string '1(10) 00069- rob c pettit 54' Id like to know if
its possile to replaces spaces with - only when preceded with a letter
and followed with a letter. Giving '1(10) 00069- rob-c-pettit 54'

Regex.Replace("1(10) 00069- rob c pettit 54", @"(?<=\w) (?=\w)", "-");

Learn to love the Regex class. But don't love it too much, because some
things aren't naturally done with regexes. This particular problem is, though.
 
Jeroen said:
Regex.Replace("1(10) 00069- rob c pettit 54", @"(?<=\w) (?=\w)", "-");

Learn to love the Regex class. But don't love it too much, because some
things aren't naturally done with regexes. This particular problem is,
though.
There's an error in the regex above, incidentally, which you should be able
to fix yourself now. Consult the documentation.
 
Hi, thanks for your reply. Ive just been looking at books on amazon re
regular expressions, time to invest. I got 1(10) 00069- rob-c-
pettit-54 returned, can I stop the pettit-54 from occuring.
Regards Robert
 
TRY
Regex.Replace("1(10 00069- rob c pettit 54", @"(?<=[a-zA-Z]) (?=[a-zA-Z])",
"-");



\w matches any word character. Equivalent to the Unicode character
categories [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant
behavior is specified with the ECMAScript option, \w is equivalent to
[a-zA-Z_0-9].
since you dont want the "word" to include digits you define a new set of
character as [a-zA-Z]
 
Thankyou for your reply, works perfect. A new subject for me and a big
topic by the looks of it.
Regards Robert
 
Back
Top