2

I'm trying to match usernames from a file. It's kind of like this:

username=asd123 password123

and so on.

I'm using the regular expression:

username=(.*) password

To get the username. But it doesn't match if the username would be say and[ers] or similar. It won't match the brackets. Any solution for this?

Accatyyc
  • 5,798
  • 4
  • 36
  • 51
  • How can I escape them if I don't know they're coming? The usernames are entered by the users so I don't know what they are beforehand. – Accatyyc Aug 12 '10 at 00:20

2 Answers2

1

Your Regular Expression is correct. Instead, you may try this one:

username=([][[:alpha:]]*) password

[][[:alpha:]] means ] and [ and [:alpha:] are contained within the brackets.

Sadeq
  • 7,795
  • 4
  • 34
  • 45
  • No.. [] is an empty character class. – jtbandes Aug 12 '10 at 01:20
  • 1
    This approach is not a mistake... `]` after `[` is known as a regular character in my example... So `[]` is not interpreted as `[]` and it is not an empty character class in my regular expression. you can read more info at: http://en.wikibooks.org/wiki/Regular_Expressions/Regular_Expression_Syntaxes – Sadeq Aug 12 '10 at 02:05
1

I would probably use the regular expression:

username=([a-zA-Z0-9\[\]]+) password

Or something similar. Notes regarding this:

  • Escaping the brackets ensures you get a literal bracket.
  • The a-zA-Z0-9 spans match alphanumeric characters (as per your example, which was alphanumerc). So this would match any alphanumeric character or brackets.
  • The + modifier ensures that you match at least one character. The * (Kleene star) will allow zero repetitions, meaning you would accept an empty string as a valid username.
  • I don't know if RegexKitLite allows POSIX classes. If it does, you could use [:alnum:] in place of a-zA-Z0-9. The one I gave above should work if it doesn't, though.

Alternatively, I would disallow brackets in usernames. They're not really needed, IMO.

eldarerathis
  • 35,455
  • 10
  • 90
  • 93
  • Thanks, I'll look into this. And it's not up to me to disallow brackets, these usernames have existed for years and brackets have always been allowed, unfortunately :( – Accatyyc Aug 12 '10 at 08:49
  • You may also want to post a little more code, if possible. It does seem unusual that the `(.*)` expression isn't matching here, so I would definitely check how you are parsing the file and passing the string into the regex. It could be an issue of the string itself being malformed when you encounter a bracket. – eldarerathis Aug 12 '10 at 13:08