regex - Java String tokens -
i have string line
string user_name = "id=123 user=aron name=aron app=application";
and have list contains: {user,cuser,suser}
and have user part string. have code this
list<string> username = config.getconfig().getlist(configuration.att_cef_user_name); string result = null; (string param: user_name .split("\\s", 0)){ for(string user: username ){ string userparam = user.concat("=.*"); if (param.matches(userparam )) { result = param.split("=")[1]; } } }
but problem if string contains spaces in user_name
, not work. ex:
string user_name = "id=123 user=aron nicols name=aron app=application";
here user
has value aron nicols
contain spaces. how can write code can me exact user
value i.e. aron nicols
if want split on spaces right before tokens have =
righ after such user=...
maybe add look ahead condition like
split("\\s(?=\\s*=)")
this regex split on
\\s
space(?=\\s*=)
has 0 or more*
non-space\\s
characters ends=
after it. look-ahead(?=...)
zero-length match means part matched not included in in result split not split on it.
demo:
string user_name = "id=123 user=aron nicols name=aron app=application"; (string s : user_name.split("\\s(?=\\s*=)")) system.out.println(s);
output:
id=123 user=aron nicols name=aron app=application
from comment in other answer seems =
escaped \
shouldn't treated separator between key=value
part of value. in case can add negative-look-behind mechanism see if before =
no \
, (?<!\\\\)
right before require =
not have \
before it.
btw create regex match \
need write \\
in java need escape each of \
create \
literal in string why ended \\\\
.
so can use
split("\\s(?=\\s*(?<!\\\\)=)")
demo:
string user_name = "user=dist\\=name1, xyz src=activedirectorydomain ip=10.1.77.24"; (string s : user_name.split("\\s(?=\\s*(?<!\\\\)=)")) system.out.println(s);
output:
user=dist\=name1, xyz src=activedirectorydomain ip=10.1.77.24
Comments
Post a Comment