问题
I parse some logs and in some case user name shown as FirstName.LastName in the other cases it shown as FLastName. I am just wonder if it is possible to parse both to names to FLastName. For example Joe.Doe and JDoe should both yeild JDoe. Thank you.
回答1:
This will do it:
(.)(?:[^\.]*\.)(.+)$
Basically it grabs the first character and then allows for multiple characters followed by a dot and then grabs the rest. The replacement string would be:
$1$2
But that depends on your regex tool that you're using.
Try it on RegExr (thanks stema, I didn't know about this site).
回答2:
Not sure what regex platform you are using but this will work in sed:
sed 's/\([a-z[A-Z]\).*\.\(.*\)$/\1\2/'
For strings "FirstName.LastName
and FLastName
it gives output:
FLastName
回答3:
My solution, (but the other two will work as well)
^([a-zA-Z])(?:.*\.)?(.*)$
See online here on Regexr
It matches the first letter, then the following part till the dot is optional. At last matches the string till the end. The first letter is in group 1 and the LastName is in group 2.
So replace with $1$2 (or \1\2, depending on your regex engine)
来源:https://stackoverflow.com/questions/5994870/regex-to-parse-first-and-last-name