开发者

RegEx help tokenizing a string

开发者 https://www.devze.com 2023-02-04 09:19 出处:网络
Could anyone tell me how I can take this: (King\'s_Cross_St_Pancras, Farringdon, Hammersmith_&_City_Line)

Could anyone tell me how I can take this: (King's_Cross_St_Pancras, Farringdon, Hammersmith_&_City_Line)

And split it into:

array[0]: King's_Cross_St_Pancras
array[1]: Farringdon
array[2]: Hammersmith_&_City_Line

The rege开发者_Python百科x should also account for < > non-word characters too. I have tried to make the regex using: "\b(<>&')?" .. this is however completely useless.

Please help


There's no need to use a regular expression here. Strip the () using String.substring(), then split the string into tokens using String.split(). Although technically this is also a regex solution, as String.split() takes a regex. :)

String s = "(King's_Cross_St_Pancras, Farringdon, Hammersmith_&_City_Line)";
s = s.substring(1, s.length()-1);
String tokens[] = s.split(", ");

Result:

King's_Cross_St_Pancras
Farringdon
Hammersmith_&_City_Line

http://ideone.com/zSDN5


You can do this easier and quicker without an RegEx:

String str = "(King's_Cross_St_Pancras, Farringdon, Hammersmith_&_City_Line)";
String result[] = str.substring(1, str.length()-1).split(",");
0

精彩评论

暂无评论...
验证码 换一张
取 消