我有这个字符串:
[Provider].[Provider]=[ProviderArea].&[X12: WALES]
我只想抓住X12
一部分。
我试过了:
(?<=: )\w+(?=\]$)
但是,这只得到WALES
.
我也试过:
^[^:]+:\s?
但这会在冒号之前(包括冒号)得到整个字符串。
我哪里错了?
如果您不想在 and 之间找到单词 ( \\w+
) &[
,:
那么您可以使用环视机制
(?<=&\\[)\\w+(?=:)
试试这个:
&\[([^:]+): [^]]+\]
& # a literal &, followed by
\[ # a literal [, followed by
( # begin capture
[^:]+ # one or more characters which are not a colon
) # end capture, followed by
: # a colon and a space (not shown), followed by
[^]]+ # one or more characters which are not a closing bracket, followed by
\] # a literal ]
在 Java 字符串中:
final Pattern p = Pattern.compile("&\\[([^:]+): [^]]+\\]");
final Matcher m = p.matcher(input);
if (m.find())
// result is in m.group(1)
我会使用以下正则表达式 \.&\[(. ): 。] 并检索组号 1。
Pattern pattern = Pattern.compile("\\.&\\[(.*): .*]");
Matcher matcher = pattern.matcher("[Provider].[Provider]=[ProviderArea].&[X12: WALES]");
String result = null;
if(matcher.find())
result = matcher.group(1);
if("X12".equals(result))
System.out.print("Good expression");
else
System.out.print("not good");