Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match any character except a backslash

Tags:

regex

ruby

How can i say "all symbols except backslash" in Ruby character class?

/'[^\]*'/.match("'some string \ hello'")  => should be nil

Variant with two backslashed doesn't work

/'[^\\]*'/.match("'some string \ hello'")  => 'some string \ hello' BUT should be nil
like image 388
Vladimir Tsukanov Avatar asked Jul 24 '12 20:07

Vladimir Tsukanov


People also ask

How to match any character using regex?

1. Match any character using regex Pattern Description “.” Matches only a single character. “A.B” Matches any character at second place in ... “.*” Matches any number of characters.

How do I match any characters except a double-quote without backslash?

How do I match any characters except a double-quote NOT preceded by a backslash? So: match quotes, and inside them: every character except a quote ( [^"]) or an escaped quote ( " ), arbitrarily many times ( * ). As chaos mentioned, you probably also want to handle double-backslashes separately (although that wasn't specified by the OP).

How do you match a dot in regular expression?

By default, the '.' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character. To create more meaningful patterns, we can combine the dot character with other regular expression constructs. .

What is a character class in regex?

A character class allows one to specify a specific set (or class) of characters that are allowed at a particular location within a match. The set of characters is enclosed by an opening [ Edit with Regexity and closing ] Edit with Regexity square bracket.


1 Answers

Your problem is not with your regex; you got that right. Your problem is that your test string does not have a backslash in it. It has an escaped space, instead. Try this:

str = "'some string \\ hello'"
puts str                 #=> 'some string \ hello'
p /'[^\\]*'/.match(str)  #=> nil
like image 169
Phrogz Avatar answered Oct 22 '22 06:10

Phrogz