简体   繁体   中英

regular expression from string

I need to use regular expression to get some values from the String. Thing is, that it is quite complicated for me.

For example i have a string like this:

oneWord [first, second, third]

My output should be:

first
second
third

So i need words which are between [ and ]. Plus there can be a different number of words between [].

Tried using some regex creator, but that wasn't very accurate:

String re1=".*?";   // Non-greedy match on filler
String re2="(?:[a-z][a-z]+)";   // Uninteresting: word
String re3=".*?";   // Non-greedy match on filler
String re4="((?:[a-z][a-z]+))"; // Word 1
String re5=".*?";   // Non-greedy match on filler
String re6="((?:[a-z][a-z]+))"; // Word 2
String re7=".*?";   // Non-greedy match on filler
String re8="((?:[a-z][a-z]+))"; // Word 3

I would do it like this, in just one line:

String[] words = str.replaceAll(".*\\[|\\].*", "").split(", ");

The first replaceAll() call strips off the leading and trailing wrapper, and the split() breaks up what's left into separate words.

You could try the below regex and get the words you want from group index 1.

(?:\[|(?<!^)\G),? *(\w+)(?=[^\[\]]*\])

DEMO

Java regex would be,

(?:\\[|(?<!^)\\G),? *(\\w+)(?=[^\\[\\]]*\\])

Example:

String s = "oneWord [first, second, third] foo bar [foobar]";
Pattern regex = Pattern.compile("(?:\\[|(?<!^)\\G),? *(\\w+)(?=[^\\[\\]]*\\])");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group(1));
}

Output:

first
second
third
foobar

You should use this string.

String[] words = str.replaceAll(". \\[|\\]. ", "").split(", ");

Hope it helps.

You can do it easily with method split.

String string = [first, second, third];
String[] parts = string.split(",");
String part1 = parts[0]; // first
String part2 = parts[1]; // second
String part3 = parts[2]; // third

if it dont work for you, please tell me that I will debug your regular expression.

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