简体   繁体   English

字符串的正则表达式

[英]regular expression from string

I need to use regular expression to get some values from the String. 我需要使用正则表达式从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. 第一个replaceAll()调用剥离了前导和尾随包装器, split()将剩下的内容拆分为单独的单词。

You could try the below regex and get the words you want from group index 1. 您可以尝试以下正则表达式并从组索引1中获取所需的单词。

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

DEMO DEMO

Java regex would be, Java正则表达式会是,

(?:\\[|(?<!^)\\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(", "); 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. 如果它不适合你,请告诉我,我将调试你的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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