简体   繁体   中英

How do I use regex to split a string into characters?

I need to learn RegEx but don't have time to figure this out right now. -- So I'm attempting exploit the community's capabilities.

I have a string containing a list of acceptable 1-character comment variables.

String comments = "#;";

And I want:

String[] parsedComments = {"#", ";"};

What RegEx string will solve my problems?

String[] parsedComments = comments.split(/*  "???"  */);

Why do you want to use a regex? Try String.toCharArray() for example.

This should do it, among other weird hacks:

String[] parsedComments = comments.split("(?!^)");

It's hardly a job for regex, though. May as well just iterate across the string and build an array out of each 1-character substring.

First, why do you need to break them into an array? A String has almost the exact same methods available to getting chars at indexes and virtually the same performance.

But, to answer your question:

string.split("");

This will give you an extra empty string at the first pos of the resulting array.

I misunderstood you in my original answer. You don't want Regex. Regex is used to find patterns, and you just want to split. You could use an empty string, but that will return an empty string as well as the characters.

Just access through the index.

I tried to add this as a comment to "Daniel" and "Lazarus", but I don't have enough reputation points yet... unless I am misunderstanding you, you are saying to access the original string using the index. You cannot do that in Java.

String foo = "abcde";
String bee = foo[1]; // not valid

If I have misunderstood you, I apologize. If not, I wanted to clarify that for posterity. :-)

只需使用comments [0],comments [1] ... comments [ n ]访问字符串索引

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