简体   繁体   中英

JavaScript: How to pull out a string from a URL using a regular expression

In java, I have this URL as a string:

window.location.href = 
"http://localhost:8080/bladdey/shop/c6c8262a-bfd0-4ea3-aa6e-d466a28f875/hired-3";

I want to create a javascript regular expression to pull out the following string:

c6c8262a-bfd0-4ea3-aa6e-d466a28f875

To find left hand marker for the text, I could use the regex:

window\.location\.href \= \"http\:\/\/localhost:8080\/bladdey\/shop\/

However, I don't know how to get to the text between that and /hired3"

What is the best way to pull out that string from a URL using javascript?

You could split the string in tokens and look for a string that has 4 occurrences of - .

Or, if the base is always the same, you could use the following code:

String myString = window.location.href;
myString = myString.substring("http://localhost:8080/bladdey/shop/".Length());
myString = myString.subString(0, myString.indexOf('/'));

Use a lookahead and a lookbehind,

(?<=http://localhost:8080/bladdey/shop/).+?(?=/hired3)

Check here for more information.

Also, there is no need to escape the : or / characters.

You can use capturing groups to pull out some content of your string. In your case :

   Pattern pattern = Pattern.compile("(http://localhost:8080/bladdey/shop/)(.+)(/hired-3)");
    Matcher matcher = pattern.matcher(string);
    if(matcher.matches()){
       String value = matcher.group(2);
    }

You need a regex, and some way to use it...

  String theLocation = "http://localhost:8080/bladdey/shop/c6c8262a-bfd0-4ea3-aa6e-d466a28f8752/hired-3";
  String pattern = "(?</bladdey/shop/).+?(?=/hired3)";

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(line);
  if (m.find( )) {
     System.out.println("Found value: " + m.group(0) );
  } else {
     System.out.println("NO MATCH");
  }

note - this will still work when you change the host (it only looks for bladdey/shop/ )

String param = html.replaceFist("(?s)^.*http://localhost:8080/bladdey/shop/([^/]+)/hired-3.*$", "$1");

if (param.equals(html)) {
    throw new IllegalStateException("Not found");
}
UUID uuid = new UUID(param);

In regex:

  • (?s) let the . char wildcard also match newline characters.
  • ^ begin of text
  • $ end of text
  • .* zero or more (*) any (.) characters
  • [^...]+ one or more (+) of characters not (^) being ...

Between the first parentheses substitutes $1 .

Well if you want to pull out GUID from anything:

var regex = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{11,12}/i

It should really be {12} but in your url it is malformed and has just 15.5 bytes of information.

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