This discussion is archived
3 Replies Latest reply: Nov 4, 2006 12:04 AM by 807607 RSS

regex - match single character at end of a line

807607 Newbie
Currently Being Moderated
I have a list of words, one to each line, and each word has a single character at the end that denotes its part of speech. Therefore, I'm trying to write a regular expression that will match a single character at the end of line, so I can parse through this data.

I can't just use something like [N$] because it will just match the first 'N' from the end of the line, not just lines that end in N. So I want something that will match a single character at the end of a line.

So if my data contained something like:
BounceN
BouncerV

I would want the regular expression to match 'N' at the end of a line to match just "BounceN" and not "BouncerV".

Thanks for you time, and thanks in advance to anyone that can help.
  • 1. Re: regex - match single character at end of a line
    807607 Newbie
    Currently Being Moderated
    I can't just use something like [N$] because it will
    just match the first 'N' from the end of the line,
    not just lines that end in N.
    I'm not sure I understand this statement but I think it is wrong.
    So I want something
    that will match a single character at the end of a
    line.
    You have it if you combine with Pattern.find()

    >
    So if my data contained something like:
    BounceN
    BouncerV

    I would want the regular expression to match 'N' at
    the end of a line to match just "BounceN" and not
    "BouncerV".
    You have it but it looks to me like you need String.charAt() rather than a regex.
  • 2. Re: regex - match single character at end of a line
    807607 Newbie
    Currently Being Moderated
    Actually, the regex "[N$]" will match either an 'N' or a dollar sign anywhere in the target string. If you want to match lines that end with 'N', get rid of the square brackets:
      Pattern p = Pattern.compile("N$");
      Matcher m = p.matcher("");
      for (String str : strings)
      {
        if (m.reset(str).find())
        {
          // etc.
        }
      }
    If you want to find out what the last character in the string is, it's easier to do it without using a regex:
      char c = str.charAt(str.length() - 1);
  • 3. Re: regex - match single character at end of a line
    807607 Newbie
    Currently Being Moderated
    Actually, the regex "[N$]" will match either an 'N'
    or a dollar sign anywhere in the target string.
    Well spotted! The original post now makes sense. I assumed that that [] pair were just being used to delimit the regex and not part of it!