开发者

Regex to match part of a string

开发者 https://www.devze.com 2022-12-12 12:56 出处:网络
Regex fun again... Take for example http://something.com/en/page I want to test for an exact match on /en/ including the forward sla开发者_StackOverflow社区shes, otherwise it could match \'en\' from

Regex fun again...

Take for example http://something.com/en/page

I want to test for an exact match on /en/ including the forward sla开发者_StackOverflow社区shes, otherwise it could match 'en' from other parts of the string.

I'm sure this is easy, for someone other than me!

EDIT:

I'm using it for a string.match() in javascript


If you're trying to match /en/ specifically, you don't need a regular expression at all. Just use your language's equivalent of contains to test for that substring.

If you're trying to match any two-letter part of the URL between two slashes, you need an expression like this:

/../

If you want to capture the two-letter code, enclose the periods in parentheses:

/(..)/

Depending on your language, you may need to escape the slashes:

\/..\/
\/(..)\/

And if you want to make sure you match letters instead of any character (including numbers and symbols), you might want to use an expression like this instead:

/[a-z]{2}/

Which will be recognized by most regex variations.

Again, you can escape the slashes and add a capturing group this way:

\/([a-z]{2})\/

And if you don't need to escape them:

 /([a-z]{2})/

This expression will match any string in the form /xy/ where x and y are letters. So it will match /en/, /fr/, /de/, etc.

In JavaScript, you'll need the escaped version: \/([a-z]{2})\/.


Well it really depends on what programming language will be executing the regex, but the actual regex is simply

/en/

For .Net the following code works properly:

string url = "http://something.com/en/page";

bool MatchFound = Regex.Match(url, "/en/").Success;

Here is the JavaScript version:

var url = 'http://something.com/en/page';
if (url.match(/\/en\//)) {
    alert('match found');
}
else {
    alert('no match');
}

DUH

Thank you to Welbog and Chris Ballance to making what should have been the most obvious point. This does not require Regular Expressions to solve. It simply is a contains statement. Regex should only be used where it is needed and that should have been my first consideration and not the last.


You may need to escape the forward-slashes...

/\/en\//


Any reason /en/ would not work?


/\/en\// or perhaps /http\w*:\/\/[^\/]*\/en\//


You don't need a regex for this:

location.pathname.substr(0, 4) === "/en/"

Of course, if you insist on using a regex, use this:

/^\/en\//.test(location.pathname)
0

精彩评论

暂无评论...
验证码 换一张
取 消