下面列出了java.util.regex.Matcher#matches ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static long parseDurationMS(CharSequence durationString) {
if (durationString == null) {
return -1L;
}
Matcher m = RFC2445_DURATION.matcher(durationString);
if (!m.matches()) {
return -1L;
}
long durationMS = 0L;
for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.length; i++) {
String fieldValue = m.group(i + 1);
if (fieldValue != null) {
durationMS += RFC2445_DURATION_FIELD_UNITS[i] * Integer.parseInt(fieldValue);
}
}
return durationMS;
}
/**
* 该方法将中文字之间加上空格。
*
* @param input
* @return
*/
public static String chineseTranslate(String input) {
StringBuffer newStr = new StringBuffer("");
java.util.regex.Pattern p = java.util.regex.Pattern
.compile("[\u4E00-\u9FA5]");
char[] chars = new char[1];
Matcher m;
for (int i = 0; i < input.length(); i++) {
chars[0] = input.charAt(i);
m = p.matcher(new String(chars));
if (m.matches())
newStr.append(" ").append(input.charAt(i)).append(" ");
else
newStr.append(input.charAt(i));
}
// java.lang.System.out.println("#" + newStr.toString());
// strTemp = newStr.toString().replaceAll("\\s{2,}", " ");//
// 把2个连续的空格替换成一个空格。
// strTemp = strTemp.replaceAll("^\\s*|\\s*$", ""); // 把头和尾的空格去掉。
return newStr.toString();
}
private Map<String,String> parsePipShowOutput(Path _file) throws IOException {
final Map<String,String> props = new HashMap<String,String>();
// The pattern to search for
final Pattern pattern = Pattern.compile("^([^:]*):(.*)$");
// Read line by line
final BufferedReader reader = new BufferedReader(new FileReader(_file.toFile()));
String line;
while( (line=reader.readLine())!=null ) {
final Matcher m = pattern.matcher(line);
if(m.matches())
props.put(m.group(1).trim(), m.group(2).trim());
}
reader.close();
return props;
}
/**
* Try to parse an {@link ArrayType} string representation (either canonical form or not).
*
* @param repo a {@link Type} parsers repository
* @param str a string
* @return an {@link ArrayType} instance is packed as {@link Optional} value,
* or {@link Optional#empty()} instead
* @throws NullPointerException if a {@code str} is {@code null}
* @throws IllegalArgumentException if an {@link ArrayType} has invalid
* input or not a {@link StaticType} wrapped type
* @see #getCanonicalName()
*/
@SuppressWarnings("unchecked")
public static Optional<ArrayType> from(Type.Repository repo, String str) {
if (!str.endsWith(NAME_POSTFIX) || str.endsWith(EX_NAME_POSTFIX))
return Optional.empty();
Matcher matcher = NAME_PATTERN.matcher(str);
if (!matcher.matches())
throw new IllegalArgumentException("Wrong array type format: " + str);
Optional<Type> type = repo.search(matcher.group(1));
if (!type.isPresent())
throw new IllegalArgumentException(
"Unknown array wrapped type: " + matcher.group(1));
if (type.get().isDynamic())
throw new IllegalArgumentException(
"Array wrapped type is not static: " + type.get());
String digits = matcher.group(2);
return Optional.of(new ArrayType(
(StaticType) type.get(), Integer.parseInt(digits)));
}
public static MD5JointData parseLine(String line) {
MD5JointData result = null;
Matcher matcher = PATTERN_JOINT.matcher(line);
if (matcher.matches()) {
result = new MD5JointData();
result.setName(matcher.group(1));
result.setParentIndex(Integer.parseInt(matcher.group(2)));
float x = Float.parseFloat(matcher.group(3));
float y = Float.parseFloat(matcher.group(4));
float z = Float.parseFloat(matcher.group(5));
result.setPosition(new Vector3f(x, y, z));
x = Float.parseFloat(matcher.group(6));
y = Float.parseFloat(matcher.group(7));
z = Float.parseFloat(matcher.group(8));
result.setOrientation(new Vector3f(x, y, z));
}
return result;
}
/**
* Groups the operations by regex group. The key of the Multimap is the group name.
* The value of the Multimap is a PathOperation
*
* @param allOperations all operations
* @param headerPattern regex pattern used for determining headers
* @return Operations grouped by regex
*/
public static Multimap<String, SwaggerPathOperation> groupOperationsByRegex(List<SwaggerPathOperation> allOperations, Pattern headerPattern) {
Multimap<String, SwaggerPathOperation> operationsGroupedByRegex = LinkedHashMultimap.create();
for (SwaggerPathOperation operation : allOperations) {
String path = operation.getPath();
Matcher m = headerPattern.matcher(path);
if (m.matches() && m.group(1) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Added path operation '{}' to header '{}'", operation, m.group(1));
}
operationsGroupedByRegex.put(m.group(1), operation);
} else {
if(logger.isWarnEnabled()) {
logger.warn("Operation '{}' does not match regex '{}' and will not be included in output", operation, headerPattern.toString());
}
}
}
return operationsGroupedByRegex;
}
public Country findCountryByAtPath(final String atPath) {
if(atPath == null) {
return null;
}
Matcher matcher = PATTERN_COUNTRY_CODE_FROM_ATPATH.matcher(atPath);
if(!matcher.matches()) {
return null;
}
final String reference = matcher.group("reference");
return findCountry(reference);
}
@Override
public boolean validate(String statement, String namePrefix) throws DatabaseScriptException {
Matcher matcher = ALTER_TABLE_PATTERN.matcher( statement);
if( !matcher.matches()) {
if( logger.isInfoEnabled())
logger.info( "Statement does not match regular expression");
return false;
}
String tableName = matcher.group( 1);
String columnName = matcher.group( 2);
if( logger.isDebugEnabled()) {
logger.debug( "table name: " + tableName);
logger.debug( "column name: " + columnName);
}
if( tableNameHasPluginPrefix( tableName, namePrefix)) {
validateTableName( tableName, namePrefix);
} else {
validateColumnName( columnName, namePrefix);
}
return true;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void messageArrived(String topic, MqttMessage msg) {
if (!commandCallbacks.isEmpty()) {
/*
* Only check whether the message is a command if a callback has been defined,
* otherwise it is a waste of time as without a callback there is nothing to
* process the generated command.
*/
Matcher matcher = COMMAND_PATTERN.matcher(topic);
if (matcher.matches()) {
String command = matcher.group(1);
String format = matcher.group(2);
MessageCodec codec = messageCodecsByFormat.get(format);
// Check that a codec is registered
if (codec == null) {
LOG.warn("Unable to decode command from format " + format);
}
MessageInterface message = codec.decode(msg);
Command cmd = new Command(command, format, message);
LOG.debug("Command received: " + cmd.toString());
CommandCallback callback = commandCallbacks.get(codec.getMessageClass());
if (callback != null) {
callback.processCommand(cmd);
}
}
}
}
private String getGraphPathWithVersion() {
Matcher matcher = versionPattern.matcher(this.graphPath);
if (matcher.matches()) {
return this.graphPath;
}
return String.format("%s/%s", this.version, this.graphPath);
}
private String nextEvent(StringBuffer buff) {
Matcher m = EVENT.matcher(buff);
if (m.matches()) {
String evt = m.group(1);
buff.delete(0, evt.length());
return evt;
}
return null;
}
/**
* Checks if the supplied daysOfWeek component is valid.
* @param daysOfWeekString The daysOfWeek string.
* @return true if valid; otherwise false.
**/
public static boolean isValidDaysOfWeekComponent(String daysOfWeekString) {
String daysOfWeek = null;
StringTokenizer tokenizer = new StringTokenizer(daysOfWeekString, ",");
while(tokenizer.hasMoreTokens()) {
boolean foundMatch = false;
daysOfWeek = tokenizer.nextToken();
// Check all the regular expressions.
for(int ix=0; ix<DAY_OF_WEEK_PATTERNS.length; ix++) {
if(Pattern.matches(DAY_OF_WEEK_PATTERNS[ix], daysOfWeek)) {
foundMatch = true;
}
}
// Special test for range parsing
Matcher m = Pattern.compile(DAY_OF_WEEK_PATTERNS[0]).matcher(daysOfWeek);
if(m.matches()) {
int day1 = isNumeric(m.group(1)) ? Integer.parseInt(m.group(1)) : dayMap.get(m.group(1));
int day2 = isNumeric(m.group(2)) ? Integer.parseInt(m.group(2)) : dayMap.get(m.group(2));
if(day1 > day2) {
foundMatch = false;
}
}
if(!foundMatch) {
return false;
}
}
return true;
}
private ParsedModuleStringNotation splitModuleFromExtension(String notation) {
Matcher matcher = EXTENSION_SPLITTER.matcher(notation);
boolean hasArtifactType = matcher.matches();
if (hasArtifactType && !ClientModule.class.isAssignableFrom(wantedType)) {
if (matcher.groupCount() != 2) {
throw new InvalidUserDataException("The dependency notation " + notation + " is invalid");
}
return new ParsedModuleStringNotation(matcher.group(1), matcher.group(2));
}
return new ParsedModuleStringNotation(notation, null);
}
@Override
public synchronized TextTraceContext seekEvent(ITmfLocation location) {
TextTraceContext context = new TextTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK);
if (NULL_LOCATION.equals(location) || fFile == null) {
return context;
}
try {
if (location == null) {
fFile.seek(0);
} else if (location.getLocationInfo() instanceof Long) {
fFile.seek((Long) location.getLocationInfo());
}
long rawPos = fFile.getFilePointer();
String line = fFile.getNextLine();
while (line != null) {
line = preProcessLine(line);
Matcher matcher = getFirstLinePattern().matcher(line);
if (matcher.matches()) {
setupContext(context, rawPos, line, matcher);
return context;
}
rawPos = fFile.getFilePointer();
line = fFile.getNextLine();
}
return context;
} catch (IOException e) {
Activator.logError("Error seeking file: " + getPath(), e); //$NON-NLS-1$
return context;
}
}
private String versionedStaticResourceContent(String fileRealPath, String content, String newVersion) throws IOException {
content = StringEscapeUtils.unescapeXml(content);
if(newVersion != null && newVersion.equals("1")) {
newVersion = "?" + newVersion;
}
File file = new File(fileRealPath);
List<String> contents = FileUtils.readLines(file);
for(int i = 0, l = contents.size(); i < l; i++) {
String fileContent = contents.get(i);
if(content.equals(fileContent)) {
Matcher matcher = scriptPattern.matcher(content);
if(!matcher.matches()) {
matcher = linkPattern.matcher(content);
}
if(newVersion == null) { //删除版本
content = matcher.replaceAll("$1$2$5");
} else {
content = matcher.replaceAll("$1$2$3" + newVersion + "$5");
}
contents.set(i, content);
break;
}
}
FileUtils.writeLines(file, contents);
return content;
}
/**
* Represents a single zookeeper address.
*
* @param address Must be in the format [user:[email protected]]host[:port] where [] are optional.
*/
public ZKAddress(String address) {
Matcher matcher = Pattern.compile(ADDRESS_REGEX).matcher(address);
if (!matcher.matches()) {
throw new ZKAddressException(address);
}
for (int i = 0; i < matcher.groupCount() + 1; i++) {
matcherMap.put(i, matcher.group(i));
}
setUser(matcherMap.getOrDefault(1, ""));
setPassword(matcherMap.getOrDefault(2, ""));
setAddress(matcherMap.getOrDefault(3, ""));
setPort(matcherMap.getOrDefault(4, ""));
setZkNode(matcherMap.getOrDefault(5, ""));
}
/**
* @return an external message id or null if this is not an
* external message identifier
*/
private static String getExternalMessageId(String identifier) {
Matcher m = MSG_EXTERNAL_PATTERN.matcher(identifier);
return m.matches() ? m.group(1) : null;
}
protected byte[] getMultipartBoundary(HttpRequest httpRequest) {
final String contentType = httpRequest.getFirstHeader("Content-Type");
final Matcher matcher = MULTIPART_BOUNDARY_PATTERN.matcher(contentType);
matcher.matches();
return matcher.group(1).getBytes();
}
private void testValue( int index, boolean testRegEx, String regExString ) {
String realScript = regExString;
if ( realScript == null ) {
realScript = transmeta.environmentSubstitute( wRegExScript.getText() );
}
if ( Utils.isEmpty( realScript ) ) {
if ( testRegEx ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "RegexEvalHelperDialog.EnterScript.Message" ) );
mb.setText( BaseMessages.getString( PKG, "RegexEvalHelperDialog.EnterScript.Title" ) );
mb.open();
}
return;
}
String realValue = null;
Text control = null;
switch ( index ) {
case 1:
realValue = Const.NVL( transmeta.environmentSubstitute( wValue1.getText() ), "" );
control = wValue1;
break;
case 2:
realValue = Const.NVL( transmeta.environmentSubstitute( wValue2.getText() ), "" );
control = wValue2;
break;
case 3:
realValue = Const.NVL( transmeta.environmentSubstitute( wValue3.getText() ), "" );
control = wValue3;
break;
case 4:
realValue = Const.NVL( transmeta.environmentSubstitute( wValueGroup.getText() ), "" );
control = wValueGroup;
break;
default:
break;
}
try {
Pattern p;
if ( isCanonicalEqualityFlagSet() ) {
p = Pattern.compile( regexoptions + realScript, Pattern.CANON_EQ );
} else {
p = Pattern.compile( regexoptions + realScript );
}
Matcher m = p.matcher( realValue );
boolean ismatch = m.matches();
if ( ismatch ) {
control.setBackground( guiresource.getColorGreen() );
} else {
control.setBackground( guiresource.getColorRed() );
}
if ( index == 4 ) {
wGroups.removeAll();
int nrFields = m.groupCount();
int nr = 0;
for ( int i = 1; i <= nrFields; i++ ) {
if ( m.group( i ) == null ) {
wGroups.add( "" );
} else {
wGroups.add( m.group( i ) );
}
nr++;
}
wlGroups.setText( BaseMessages.getString( PKG, "RegexEvalHelperDialog.FieldsGroup", nr ) );
}
wRegExScriptCompile.setForeground( guiresource.getColorBlue() );
wRegExScriptCompile.setText( BaseMessages
.getString( PKG, "RegexEvalHelperDialog.ScriptSuccessfullyCompiled" ) );
wRegExScriptCompile.setToolTipText( "" );
} catch ( Exception e ) {
if ( !errorDisplayed ) {
wRegExScriptCompile.setForeground( guiresource.getColorRed() );
wRegExScriptCompile.setText( e.getMessage() );
wRegExScriptCompile.setToolTipText( BaseMessages.getString(
PKG, "RegexEvalHelperDialog.ErrorCompiling.Message" )
+ Const.CR + e.toString() );
this.errorDisplayed = true;
}
}
}
protected boolean isMatchEndDirectiveText(String text){
if(ExcelUtils.isBlank(text))
return false;
Matcher matcher = getEndTag().matcher(text);
return matcher.matches();
}