How can I check if a string contains a specific charater in Regex?
How can I check i开发者_JAVA技巧f a string contains at any position one or more '/' character(s) in Regex?
Thanks.
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;
\/
escape it with a backslash, e.g. /
By escaping it with a \ (backslash).
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.
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
In c#:
String sss = "<your string>";
Regex re1 = new Regex(@".*/.*");
if (re1.IsMatch(sss)) .....
You probably want \/+
. However it depends on engine.
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;
}
精彩评论