views:

51

answers:

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?

A: 

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

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

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

PC2st
No.. [] is an empty character class.
jtbandes
I think you need to escape the `]`, or the regular expression would be interpreted as `[]` `[[:alpha:]]*`.
kiamlaluno
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
PC2st
+1  A: 

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
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
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