Regex Problem

yan1

Erfahrenes Mitglied
Hi,

ich habe folgenden String gegeben:

Code:
etc.....
Server: Apache
X-Powered-By: PHP/5.0.4
Set-Cookie: PHPSESSID=blubbblubb; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: index.php
etc....

und will jetzt die Session Id auslesen, also: "blubbblub".
Ich komme da nicht weiter, kann mir jemand wie ich das löse?

Mein bisheriger Ansatz:

Java:
    private String findPhpSessid(String resp){
        String pattern = "PHPSESSID=(.*); path";
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(resp);
        if ( matcher.groupCount() <= 0)
            throw new Error("Sessid not sent");
        
        matcher.find();
        return matcher.group();
    }

In Csharp konnte man so etwas machen: "PHPSESSID=(?<sessid>(.*)); path";
und dann mit found["sessid"] auslesen, gibt es eine solche Möglichkeit auch in Java?

Danke, Yanick
 
Hallo!

Schau mal hier:
Java:
/**
 * 
 */
package de.tutorials;

import java.util.regex.Pattern;

/**
 * @author Thomas.Darimont
 */
public class RequestHeaderRegexExample {

  /**
   * @param args
   */
  public static void main(String[] args) {
    String requestHeader = "Server: Apache\n" + "X-Powered-By: PHP/5.0.4\n"
      + "Set-Cookie: PHPSESSID=blubbblubb; path=/\n" + "Expires: Thu, 19 Nov 1981 08:52:00 GMT\n"
      + "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\n" + "Pragma: no-cache\n"
      + "Location: index.php;\n";

    System.out.println(requestHeader);

    System.out.println(Pattern.compile(".*PHPSESSID=([^;]*);.*", Pattern.DOTALL).matcher(requestHeader)
      .replaceAll("$1"));

  }
}

Gruß Tom
 
Hey, danke!

Das ging ja schnell..

Ich hab übrigens ne zweite Lösung gefunden:

Java:
private String findPhpSessid(String resp){
        String pattern = "PHPSESSID=(.*); path";
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(resp);
        if ( matcher.groupCount() <= 0)
            throw new Error("Sessid not sent");
        
        matcher.find();
        return matcher.group(1);
    }

Thx, Yanick
 

Neue Beiträge

Zurück