[英]Regular Expression without braces
i have the following sample cases : 我有以下示例案例:
I want to form a(only one) regular expression pattern, to which the above examples are passed returns me "Sample"
and "10,25"
. 我想形成一个(仅一个)正则表达式模式,上面的示例传递给它,返回
"Sample"
和"10,25"
。
Note: Input strings do not include Quotes. 注意:输入字符串不包含引号。
I came up with the following expression (?<=\\[)(.*?)(?=\\])
, this satisfies the second case and retreives me only "10,25"
but when the first case is matched it returns me blank. 我想出了以下表达式
(?<=\\[)(.*?)(?=\\])
,它满足第二种情况,并且只返回"10,25"
但是当第一种情况匹配时,返回我空白。 I want "Sample" to be returned? 我想退还“样品”吗? can anyone help me.
谁能帮我。
C#. C#。
As far as I can tell, the below regex should help: 据我所知,下面的正则表达式应该有所帮助:
Regex regex = new Regex(@"^\w+|[[](\w)+\,(\w)+[]]$");
This will match multiple words, or 2 words (alphanumeric) separated by commas and inside square brackets. 这将匹配多个单词,或2个单词(字母数字),中间用逗号隔开,并在方括号内。
here you go, a small regex using a positive lookbehind, sometime these are very handy 在这里,使用正向后的小正则表达式,有时候这些非常方便
Regex 正则表达式
(?<=^|\[)([\w,]+)
Test string 测试字符串
Sample
[10,25]
Result 结果
MATCH 1 比赛1
Sample
Sample
MATCH 2 比赛2
10,25
10,25
try at regex101.com 尝试在regex101.com
if "
is included in your original string, use this regex, this will look for "
mark as well, you may choose to remove ^|
如果原始字符串中包含
"
,请使用此正则表达式,它也会查找"
标记,您可以选择删除^|
from lookup if "
mark is always included or you may choose to leave it as it is if your text has combination of with and without "
marks 从查找开始,如果始终包含
"
标记,或者如果您的文本具有带有和不带有"
标记的组合,则可以选择保留它
Regex 正则表达式
(?<=^|\[|\")([\w,]+)
try at regex101.com 尝试在regex101.com
One Java example: 一个Java示例:
// String input = "Sample";
String input = "[10,25]";
String text = "[^,\\[\\]]+";
Pattern pMod = Pattern.compile("(" + text + ")|(?>\\[(" + text + "," + text + ")\\])");
Matcher mMod = pMod.matcher(input);
while (mMod.find()) {
if(mMod.group(1) != null) {
System.out.println(mMod.group(1));
}
if(mMod.group(2)!=null) {
System.out.println(mMod.group(2));
}
}
if input is "[hello&bye,25|35]", then the output is hello&bye,25|35 如果输入为“ [[hello&bye,25 | 35]””,则输出为“ hello&bye,25 | 35”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.