简体   繁体   中英

How would I get a specific portion of a regex expression?

I'm trying to get the domain name of a URL. I could run a series of if statements that check what the url contains, but ideally I'd use a regex.

The following regex ^[^.]*:[\\/]{0,2}[w]{0,3}[.]{0,1}[\\w]*.[\\w\\W]*$ does enough of what I want.

This applies for: https://www.google.com http://www.google.com www.google.com

Now I just want to get google.com from this regex, but unsure how to do that.

Refering to the comment of @PM 77-1

RegExp.prototype.exec() ( mdn-docs ) gives you a result array, where each index corresponds to the »capturing groups« in your expression:

var
  input = 'Hello',
  finder = /^(H)ell(o)/m,
  match = finder.exec(input);

console.log(match) // ["Hello", "H", "o"]

Index 0 is the whole match, each following item is the result of the capturing groups, which are established by (…) in the regular expression and ordered from left to right in appearance in the expression.

If I'm understanding your question correctly,

Try this ^([^.]*:[\\/]{0,2}[w]{0,3}[.]{0,1}){0,1}[\\w]*.[\\w\\W]*$

To Explain:

I decided to group the part that looks for the protocol and the www part [^.]*:[\\/]{0,2}[w]{0,3}[.]{0,1} , and made it optional by grouping it together by wrapping it in parenthesis (...) and adding a 0 or 1 times clause for the whole group {0,1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM