Regular expression from string
I need to use regex to get some values ββfrom String. The thing is, it's pretty difficult for me.
For example, I have a line like this:
oneWord [first, second, third]
My output should be:
first
second
third
I want words that are between [and]. In addition, there may be a different number of words between [].
Tried using some regex maker but it 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
+3
source to share
4 answers
You can try the following regex and get the words you want from group 1 index.
(?:\[|(?<!^)\G),? *(\w+)(?=[^\[\]]*\])
Java regex will 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
+2
source to share
You can do this easily with the split method.
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 doesn't work for you, tell me I'll debug your regex.
0
source to share