Regex to match user and user@domain

Henfo :

A user can login as "user" or as "user@domain". I only want to extract "user" in both cases. I am looking for a matcher expression to fit it, but im struggling.

final Pattern userIdPattern = Pattern.compile("(.*)[@]{0,1}.*");
final Matcher fieldMatcher = userIdPattern.matcher("user@test");
final String userId = fieldMatcher.group(1)

userId returns "user@test". I tried various expressions but it seems that nothing fits my requirement :-(

Any ideas?

Wiktor Stribiżew :

If you use "(.*)[@]{0,1}.*" pattern with .matches(), the (.*) grabs the whole line first, then, when the regex index is still at the end of the line, the [@]{0,1} pattern triggers and matches at the end of the line because it can match 0 @ chars, and then .* again matches at that very location as it matches any 0+ chars. Thus, the whole line lands in your Group 1.

You may use

String userId = s.replaceFirst("^([^@]+).*", "$1");

See the regex demo.

Details

  • ^ - start of string
  • ([^@]+) - Group 1 (referred to with $1 from the replacement pattern): any 1+ chars other than @
  • .* - the rest of the string.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130972&siteId=1