-4

Possible Duplicate:
Regex to match URL

Is there a regular expression to return a http value from a string?

So

sdfads saf as fa http://www.google.com some more text

becomes

http://www.google.com

Community
  • 1
  • 1
user701254
  • 3,935
  • 7
  • 42
  • 53

2 Answers2

2

a very simple approach:

https?://\S+

if you must check for valid urls the regex is much more complex

Sascha
  • 937
  • 6
  • 14
0

Here is simple and working example that contains retrieving searched pattern and using it to replace whole input:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regextest {

    static String[] matchThese = new String[] {
            "sdfads saf as fa http://www.google.com some more text",
            "sdfads fa http://www.dupa.com some more text",
            "should not match http://" };

    public static void main(String[] args) {

        String regex = "(https?://|www)\\S+";
        Pattern p = Pattern.compile(regex);

        System.out.println("Those that match are replaced:");
        for (String input : matchThese) {
            if (p.matcher(input).find()) {

                Matcher matcher = p.matcher(input);
                matcher.find();

                // Retrieve matching string
                String match = matcher.group();

                String output = input.replace(input, match);
                System.out.println(output);

            }
        }

    }
}
dantuch
  • 9,123
  • 6
  • 45
  • 68