简体   繁体   中英

Split strings having special characters, also without double quotes

I have been writing a web application functioning over keyword search. If the keyword contains special character( ,@#<$% etc) i want to break the keyword into two, with and without special characters.

For example @apple, should be spitted into @apple and apple. But this should be done only if the string is not enclosed within double quotes.

For the keyword, hello "@this" is just a #test

i am expecting hello "@this" is just a #test test

Is there any way to achieve this?

You can try the following and see -

String regex = "(?<!\")([,@#<$%]{1})(\\w+)(?!\")";
String input = "hello \"@this\" is just a #test";
System.out.println(input);
System.out.println(input.replaceAll(regex, "$0 $2"));

Output is

hello "@this" is just a #test
hello "@this" is just a #test test

if there are any characters between " and @
like: hello "stuff @this" is just a #test

you may use this pattern : [,@#<$%](?=(([^"]*"){2})*[^"]*$)(\\S+)
Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM