Results 1 to 4 of 4
  1. #1
    racha0601 is offline Member
    Join Date
    Apr 2009
    Posts
    3
    Rep Power
    0

    Default Regex - matching literal characters

    Im trying to match the following pattern using regex:

    The string begins with a literal '\' is followed by any number of letters and/or numbers and ends with '&0]'

    e.g. '\07761739009B&0]'

    Im trying to devise my pattern but Im not exactly sure how to work with matching literal characters, I was lead to believe a '//' would dictate that the character is literal but this doesnt work:

    Java Code:
    Pattern Serial = Pattern.compile("(\\/.*+\\&0\\])");
    Thanks in advance for any suggestions

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    What about a pattern String like so:
    Java Code:
    String patternString = "^\\\\.*\\&0\\]$";
    e.g.,
    Java Code:
    public class RegexTrial
    {
      public static void main(String[] args)
      {
        String test = "\\07761739009B&0]";
        String patternString = "^\\\\.*\\&0\\]$";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(test);
        boolean matches = matcher.matches();
        System.out.println(test);
        System.out.println(matches);
      }
    }

  3. #3
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    In a regex, you use a \ to indicate a literal, so \\ would match '\'.
    However, to use \ in a Java string, you need to escape it with another \, so double all the \ giving "\\\\" which will match '\'.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hey Racha, please don't cross-post the same question on multiple fora without notifying us that you're doing this and without providing links. It's not fair to us to ask us to possibly duplicate work that has been solved elsewhere as we're all volunteers with lives and families of our own. If you do this again, you will risk losing many potential helpers from all fora. Seriously.

Similar Threads

  1. regular expressions and string matching
    By DennyLoi in forum New To Java
    Replies: 1
    Last Post: 11-16-2007, 11:15 AM
  2. Help with signature matching
    By cachi in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 09:21 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
  •