Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex Match the first the occurrence

I've this regex (which doesn't do what i want): /^.*\/(eu|es)(?:\/)?([^#]*).*/ which actually is the js version of: /^.*/(eu|es)(?:/)?([^#]*).*/

Well, it doesn't do what i want, of course it works. :) Given this URLs:

  • http://localhost/es -> [1] = es, [2] = ''
  • http://localhost/eu/bla/bla#wop -> [1] = eu, [2] = 'bla/bla'
  • http://localhost/eu/bla/eubla -> [1] = eu, [2] = 'bla'

The first two urls work as i expected. The third one is not doing what i want. As "eu" is found later on the url, it does the match with the second eu instead of the first one. So I would like it to match this: [1] = 'eu', [2] = 'bla/eubla'

How must I do it?

Thank you. :)

like image 805
doup Avatar asked Nov 25 '09 12:11

doup


People also ask

How do you stop greedy in regex?

You make it non-greedy by using ". *?" When using the latter construct, the regex engine will, at every step it matches text into the "." attempt to match whatever make come after the ". *?" . This means that if for instance nothing comes after the ".

How do I match a specific character in regex?

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

What is DART RegExp?

A Regex or regexp (short for regular expression) is a sequence of characters that define a search pattern – it is mostly used for pattern matching with strings. Regex is supported by most programming languages. Dart provides this support through its RegExp class.

What is character class in regex?

In the context of regular expressions, a character class is a set of characters enclosed within square brackets. It specifies the characters that will successfully match a single character from a given input string.


1 Answers

Make the first * ungreedy

/^.\*?\/(eu|es)(?:\/)?([^#]\*).\*/

Btw, do you really need to escape * in javascript? Won't this work?

/^.*?\/(eu|es)(?:\/)?([^#]*).*/
like image 86
Amarghosh Avatar answered Sep 21 '22 02:09

Amarghosh