tags:

views:

83

answers:

8

How can I check if a string contains at any position one or more '/' character(s) in Regex?

Thanks.

+2  A: 

escape it with a backslash, e.g. \/

brindy
Please see my edit.
TTT
+1  A: 

By escaping it with a \ (backslash).

jarnbjo
+1  A: 

Regex APIs tend to be implementation specific so we'll need to know what language / tool you are using to give a 100% correct answer. But the quick one is simply

.*\/.*

However for this type of question, it's much more efficient to use a string searching API. Regex's are best at matching patterns. Filtering out for a single character is best done through IndexOf or a similar function.

JaredPar
the leading and trailing .* will not be necessary most of the time :)
KiNgMaR
That depends if your engine is matching from the start of the line or "searching" the text. The .* after shouldn't matter though.
avpx
+2  A: 

Do you really need to check to see if a string has '/' in it? If so, you might consider using what's probably a built-in method in whatever language you're writing your code in:

bool containsSlash = myString.IndexOf('/') >= 0;

Otherwise, you can "escape" the character by using the following notation;

\/
Ed Altorfer
A: 

In c#:

String sss = "<your string>";
Regex re1 = new Regex(@".*/.*");

if (re1.IsMatch(sss)) .....
Danail
A: 

You probably want \/+. However it depends on engine.

Matěj Grabovský
The + isn't necessary for this particular problem.
Bryan Oakley
A: 

I'll give it to you in pseudo-Perl because you didn't ask for anything specific.

$has_slash = 0;
# first slash starts regex
# backslash escape the next slash
# because it is escaped, we're looking for this as a literal slash
# end the regex pattern with the final slash
if ($string =~ /\//) {
    $has_slash = 1;
}
Autocracy
+1  A: 

You don't need a regexp for this, there are far cheaper ways to scan for a character. If you are using c I suggest you use strrchr. From the manpage:

char * strrchr(const char *s, int c);

The strrchr() function locates the last occurrence of c (converted to a char) in the string s. If c is \0', strrchr() locates the terminating \0'.

For example:

bool contains(char c, char* myString) {
  return 0 != strrchr(myString, c);
}

contains("alex", 'x'); // returns true
contains("woo\\123", '\\'); // returns true
Alex Brown