Results 1 to 5 of 5

Thread: Regex pattern

  1. #1
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Posts
    115
    Rep Power
    0

    Default Regex pattern

    I am using Regex API to filter some text. I want to find the following pattern:
    *-*.html
    A dash has to appear in the file name.

    Java Code:
    String patternStr = "[A-Za-z0-9]*.html";
    Pattern pattern = Pattern.compile(patternStr);	
    String str1;
            while ((str1 = in.readLine()) != null) {
    			Matcher matcher = pattern.matcher(str1);
    
    			while(matcher.find())
    			{
    				int start = matcher.start();
    				int end = matcher.end();
    				System.out.println(str1.subSequence(start, end));
    			}
    I don't know how to include dash (-) in the pattern string.

  2. #2
    staykovmarin is offline Senior Member
    Join Date
    Nov 2007
    Location
    Newport, WA
    Posts
    141
    Rep Power
    0

    Default

    Escape it with a double backslash (since you cant have a single backslash):
    Java Code:
    String patternStr = "*\\-*.html";

  3. #3
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Posts
    115
    Rep Power
    0

    Default

    Thanks but what does * means here. Does it mean all the possible characters? I came up with the following. Does this makes sense?

    Java Code:
    String patternStr = "[A-Za-z0-9]*\\-[A-Za-z0-9]*.html";

  4. #4
    staykovmarin is offline Senior Member
    Join Date
    Nov 2007
    Location
    Newport, WA
    Posts
    141
    Rep Power
    0

    Default

    Sorry i missed your reply :\
    This should work just fine:
    Java Code:
    		Pattern p = Pattern.compile("^(\\w+[-]\\w+).html");
    What that says is:
    ^ means the beggning of the line. it gets rid of problems like asd$#!%sd-tasd.html
    \\w A word character: [a-zA-Z_0-9]
    + one or more character
    () mean to take the entire input

    Sorry about my previous reply, i wasnt quite awake :p.

    small note: you dont need the \\ for -. You can have them, it wont hurt anything, but they are not required since - is not a special character.

  5. #5
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Posts
    115
    Rep Power
    0

Similar Threads

  1. Regex for file extension
    By gapper in forum New To Java
    Replies: 1
    Last Post: 01-31-2008, 04:59 PM
  2. Using Scanner with regex.MatchResult
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-18-2008, 03:08 PM
  3. Regex Quantifiers Example
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-10-2008, 11:44 AM
  4. Handling regular expressions using Regex
    By Java Tutorial in forum Java Tutorial
    Replies: 0
    Last Post: 01-07-2008, 01:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •