I am trying to get only the "nonpersonalizedusername" including its number or the surname. To add more detail, I'd like to accomplish something like: If there's an @-Symbol, get me everything that is in front of that @-Symbol, otherwise get me the whole string. Plus, if then there's a dot "." in it, get me everything after that dot.
Let's assume I have the following stringsof userPrincipalNames and/or displayNames:
nonpersonalizedusername004
nonpersonalizedusername019@domaina.local
prefixc.nonpersonalizedusername044@domaina.local
nonpersonalizedusername038@domainb.local
prefixa.nonpersonalizedusername002@domaina.local
prefixb.nonpersonalizedusername038@domainb.local
givenname.surname
givenname.surname@domaina.local
What I got so far is this expression:
^(?:.*?\.)?(. ?)(?:@.*)?$
but this only works, if there's an @-Symbol AND that "prefixing"-Dot in the string OR neither Dot nor @-Symbol. If there's an @-Symbol, but no prefixing-dot, I'm getting only that "local"-part from the end.
https://regex101.com/r/1aflGH/1
CodePudding user response:
You can use
^(?:[^@.]*\.)?([^@] )(?:@.*)?$
See the regex demo. The \n
is added to the negated character classes at regex101 as the test is run against a single multiline string.
Details:
^
- start of string(?:[^@.]*\.)?
- an optional sequence of any zero or more chars other than@
and.
and then a.
([^@] )
- Group 1: one or more chars other than@
char(?:@.*)?
- an optional sequence of@
and then the rest of the line$
- end of string.
CodePudding user response:
You might optionally repeat matches until the last dot before the @, and then capture the rest after that do till the @ in group 1.
^(?:[^@.]*\.)*([^@.] )
The pattern matches:
^
Start of string(?:
Non capture group[^@.]*\.
Optionally repeat matching any char except@
or.
, then match.
)*
Close non capture group and optionally repeat(
Capture group 1[^@.]
)
Close group 1
Powershell example
$s = @"
nonpersonalizedusername004
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
givenname.surname
[email protected]
"@
Select-String '(?m)^(?:[^@.\n]*\.)*([^@.\n] )' -input $s -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value}
Output
nonpersonalizedusername004
nonpersonalizedusername019
nonpersonalizedusername044
nonpersonalizedusername038
nonpersonalizedusername002
nonpersonalizedusername038
surname
surname