Vikram Singh Jadon
Vikram Singh Jadon

Reputation: 1047

Regex to select all the commas from string that do not have any white space around them

I want to select all the commas in a string that do not have any white space around. Suppose I have this string:

"He,she, They"

I want to select only the comma between he and she. I tried this in rubular and came up with this regex:

(,[^(,\s)(\s,)])

This selects the comma that I want, but also selects an s which is a character after it.

enter image description here

Upvotes: 2

Views: 263

Answers (3)

The fourth bird
The fourth bird

Reputation: 163477

In your regex (,[^(,\s)(\s,)]) you capture a comma followed by a negated character class that matches not any of the specified characters, which could also be written as (,[^)(,\s]) which will capture for example ,s in a group,

What you could do is use a positive lookahead and a positve lookbehind to check what is on the left and what is on the right is not a \S whitespace character:

(?<=\S),(?=\S)

Regex demo

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627110

In Ruby, you may use [[:space:]] to match any (Unicode) whitespace and [^[:space:]] to match any char other than whitespace. Using these character classes inside lookarounds solves the problem:

/(?<=[^[:space:]]),(?=[^[:space:]])/

See the Rubular demo

Here,

  • (?<=[^[:space:]]) - a positive lookbehind that matches a location that is immediately preceded with a non-whitespace char (if the string start position should also be matched, replace with (?<![[:space:]]))
  • , - a comma
  • (?=[^[:space:]]) - a positive lookahead that matches a location that is immediately followed with a non-whitespace char (if the string end position should also be matched, replace with (?![[:space:]])).

Upvotes: 1

vikram sahu
vikram sahu

Reputation: 179

Check the regex below and use the code hope it will help you!

re = /[^\s](,)[^\s]/m
str = 'check ,my,domain, qwe,sd'

# Print the match result
str.scan(re) do |match|
puts match.to_s
end

Check LIVE DEMO HERE

Upvotes: 0

Related Questions