Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern for checking if a string starts with a certain substring?

Tags:

c#

regex

asp.net

What's the regular expression to check if a string starts with "mailto" or "ftp" or "joe" or...

Now I am using C# and code like this in a big if with many ors:

String.StartsWith("mailto:") String.StartsWith("ftp") 

It looks like a regex would be better for this. Or is there a C# way I am missing here?

like image 627
kacalapy Avatar asked May 01 '10 16:05

kacalapy


People also ask

How do you check if a string starts with a specific substring?

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

How do you search for a RegEx pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

How do you search for a RegEx pattern at the beginning of a string in Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

Is the RegEx tag you can use to check if a string starts with a given?

Introduction – In bash, we can check if a string begins with some value using regex comparison operator =~ .


2 Answers

You could use:

^(mailto|ftp|joe) 

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" }; string s = "joe:bloggs"; bool result = prefixes.Any(prefix => s.StartsWith(prefix)); 

You could also look at the System.Uri class if you are parsing URIs.

like image 85
Mark Byers Avatar answered Sep 18 '22 08:09

Mark Byers


The following will match on any string that starts with mailto, ftp or http:

 RegEx reg = new RegEx("^(mailto|ftp|http)"); 

To break it down:

  • ^ matches start of line
  • (mailto|ftp|http) matches any of the items separated by a |

I would find StartsWith to be more readable in this case.

like image 25
Oded Avatar answered Sep 21 '22 08:09

Oded