Add space after commas only if it doesn't already?
Using negative lookahead to check no space after comma, then replace with comma and space.
print 'word word,word,word,'.gsub(/,(?![ ])/, ', ')
Add a space after commas in a string only if it doesn't exist in R
We can use gsub
to match a comma (,
) followed by any letter (([A-Za-z])
) captured as a group and then replace it with ,
followed by a space and the backreference of that captured group (\\1
)
gsub(",([A-Za-z])", ", \\1", a)
#[1] "Jack and Jill, went up the, hill, to, fetch a pail, of, water"
Or use [[:alpha:]]
gsub(",([[:alpha:]])", ", \\1", a)
#[1] "Jack and Jill, went up the, hill, to, fetch a pail, of, water"
Python regex : adding space after comma only if not followed by a number
Use this one:
newLine = re.sub(r'[,]+(?![0-9])', r' , ', newLine)
Here using negative lookahead (?![0-9])
it is checking that the comma(s) are not followed by a digit.
Your regex didn't work because you picked the comma and the next character(using ([,]+[^0-9])
) in a group and placed space on both sides.
UPDATE: If it is not only comma and other things as well, then place them inside the character class []
and capture them in group \1
using ()
newLine = re.sub(r'([,/\\]+)(?![0-9])', r' \1 ', newLine)
Add missing spaces after commas
You can use capturing group:
%s/,\(\S\)/, \1/g
\(\S\)
is being used to capture the next non-space character after a comma.
OR you can avoid the capturing using positive lookahead:
:%s/,\(\S\)\@=/, /g
Or to avoid the escaping using very magic:
:%s/\v,(\S)\@=/, /g
Add space after comma to string
Don't include arguments in your anonymous function since this is overwriting your $string value... As suggested by @RoryMcCrossan you don't need a function
var $string = 'hello,world';
$(".content").text($string.replace(/,/g, ", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"></div>
Matching regular expression on comma or space, but not both
The answer is very simple / ,?|,/g
Or if you want to remove any amount of white space before comma / *,?| /g
Or if you want go crazy go with this /\s*,\s*|\s+/g
this will replace any extra spacing before , and after it and do all good stuf as erlier.
Related Topics
Dry Way to Assign Hash Values to an Object
Optional Arguments with Default Value in Ruby
Ruby Array to JSON and Rails JSON Rendering
Traversing a Hash Recursively in Ruby
How to Customize the Table Builder Plugin for a Week Calendar
How to Declare a String with Both Single and Double Quotes in Yaml
Form_For Error Messages in Ruby on Rails
Ruby 1.9: Regular Expressions with Unknown Input Encoding
Where Should My Non-Model/Non-Controller Code Live
Howto Rank Items by Balance in Ruby on Rails
Converting a Hexadecimal Digest to Base64 in Ruby
Rvm Does Not Install Ruby 1.9.2 on Snow Leopard: 'Error Running 'Make '
Rails Unable to Convert Unpermitted Parameters to Hash