Java Code Examples for java.util.regex.Matcher
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/validation/.
Source file: RegexpValidator.java

public void validate(Model m){ if (m.get(attribute) == null) { m.addValidator(this,attribute); return; } Object value=m.get(attribute); if (!value.getClass().equals(String.class)) throw new IllegalArgumentException("attribute " + attribute + " is not String"); Pattern pattern=Pattern.compile(rule,Pattern.CASE_INSENSITIVE); Matcher matcher=pattern.matcher(value.toString()); if (!matcher.matches()) { m.addValidator(this,attribute); } }
Example 2
From project addis, under directory /application/src/main/java/org/drugis/addis/entities/.
Source file: PubMedId.java

private void setId(String id){ if (id == null || id.length() == 0) { throw new IllegalArgumentException("PubMedId may not be null or empty."); } Matcher matcher=s_onlyDigits.matcher(id); if (!matcher.matches()) { throw new IllegalArgumentException("Only digits are valid in a PubMedId, and it may not start with 0."); } d_id=id; }
Example 3
From project aether-ant, under directory /src/main/java/org/eclipse/aether/ant/tasks/.
Source file: Layout.java

public Layout(String layout) throws BuildException { Collection<String> valid=new HashSet<String>(Arrays.asList(GID,GID_DIRS,AID,VER,BVER,EXT,CLS)); List<String> tokens=new ArrayList<String>(); Matcher m=Pattern.compile("(\\{[^}]*\\})|([^{]+)").matcher(layout); while (m.find()) { if (m.group(1) != null && !valid.contains(m.group(1))) { throw new BuildException("Invalid variable '" + m.group() + "' in layout, supported variables are "+ new TreeSet<String>(valid)); } tokens.add(m.group()); } this.tokens=tokens.toArray(new String[tokens.size()]); }
Example 4
From project aether-core, under directory /aether-api/src/main/java/org/eclipse/aether/artifact/.
Source file: DefaultArtifact.java

/** * Creates a new artifact with the specified coordinates and properties. If not specified in the artifact coordinates, the artifact's extension defaults to {@code jar} and classifier to an empty string. * @param coords The artifact coordinates in the format{@code <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>}, must not be {@code null}. * @param properties The artifact properties, may be {@code null}. */ public DefaultArtifact(String coords,Map<String,String> properties){ Pattern p=Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?:([^: ]+)"); Matcher m=p.matcher(coords); if (!m.matches()) { throw new IllegalArgumentException("Bad artifact coordinates " + coords + ", expected format is <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>"); } groupId=m.group(1); artifactId=m.group(2); extension=get(m.group(4),"jar"); classifier=get(m.group(6),""); version=m.group(7); file=null; this.properties=copyProperties(properties); }
Example 5
From project agit, under directory /agit/src/main/java/com/madgag/agit/filepath/.
Source file: FilePathMatcher.java

/** * @return int array which will be overwritten on the next call - consume or copy before next invocation! */ public int[] match(CharSequence filePath){ Matcher matcher=pattern.matcher(filePath); if (matcher.find()) { for (int i=0; i < matchingLetters.length; ++i) { matchingLetters[i]=matcher.start(i + 1); } return matchingLetters; } else { return null; } }
Example 6
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.
Source file: CSVHelper.java

String fileName(String title){ StringBuilder result=new StringBuilder(); if (!Strings.isNullOrEmpty(title)) { try { Matcher matcher=Pattern.compile("([_\\-a-zA-Z0-9])*").matcher(title.toLowerCase()); while (matcher.find()) { result.append(matcher.group()); } } catch ( IllegalStateException ignore) { } } return result.length() > 0 ? result.append(".csv").toString() : SESSION_TEMP_FILE; }
Example 7
From project akela, under directory /src/main/java/com/mozilla/pig/eval/regex/.
Source file: EncodeChromeUrl.java

public String exec(Tuple input) throws IOException { if (input == null || input.size() == 0) { return null; } Matcher m=p.matcher((String)input.get(0)); return m.replaceAll("chrome%3A%2F%2Fglobal%2Flocale%2Fintl.properties"); }
Example 8
From project ALP, under directory /workspace/alp-reporter-fe/src/main/java/com/lohika/alp/reporter/fe/query/.
Source file: QueryParser.java

LinkedList<String> buildTokens(String query){ Matcher m=p.matcher(query); LinkedList<String> tokens=new LinkedList<String>(); while (m.find()) tokens.push(query.substring(m.start(),m.end())); return tokens; }
Example 9
From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/data/.
Source file: ColumnValue.java

public boolean IsImageUrl(){ try { String regex="(https?:\\/\\/.*\\.(?:png|jpg|gif|jpeg|bmp))"; Pattern patt=Pattern.compile(regex); Matcher matcher=patt.matcher(mValue); return matcher.matches(); } catch ( RuntimeException e) { return false; } }
Example 10
From project amber, under directory /oauth-2.0/common/src/main/java/org/apache/amber/oauth2/common/utils/.
Source file: OAuthUtils.java

public static String getAuthHeaderField(String authHeader){ if (authHeader != null) { Matcher m=OAUTH_HEADER.matcher(authHeader); if (m.matches()) { if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) { return m.group(2); } } } return null; }
Example 11
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.
Source file: WarningValue.java

protected void consumeHostPort(){ Matcher m=HOSTPORT_PATTERN.matcher(src.substring(offs)); if (!m.find()) parseError(); if (m.start() != 0) parseError(); offs+=m.end(); }
Example 12
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/util/.
Source file: IPRule.java

static boolean IsMatch(String ip,String ipRegexString){ Pattern pattern=ipPattern.get(ipRegexString); if (pattern == null) { pattern=Pattern.compile(ipRegexString); ipPattern.put(ipRegexString,pattern); } Matcher m=pattern.matcher(ip); return m.matches(); }
Example 13
From project amplafi-sworddance, under directory /src/main/java/com/sworddance/beans/.
Source file: BeanWorker.java

protected String getPropertyName(String methodName){ Matcher matcher=PROPERTY_METHOD_PATTERN.matcher(methodName); String propertyName; if (matcher.find()) { propertyName=matcher.group(3).toLowerCase() + matcher.group(4); } else { propertyName=null; } return propertyName; }
Example 14
From project and-bible, under directory /AndBackendTest/src/net/bible/android/device/.
Source file: SpeakTextProviderTest.java

private List<String> breakUpText(String text){ List<String> chunks=new ArrayList<String>(); Matcher matcher=breakPattern.matcher(text); int matchedUpTo=0; while (matcher.find()) { int nextEnd=matcher.end(); chunks.add(text.substring(matchedUpTo,nextEnd)); matchedUpTo=nextEnd; } chunks.add(text.substring(matchedUpTo)); return chunks; }
Example 15
From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.
Source file: Handelsbanken.java

@Override protected LoginPackage preLogin() throws BankException, ClientProtocolException, IOException { urlopen=new Urllib(); response=urlopen.open("https://m.handelsbanken.se/primary/"); Matcher matcher=reLoginUrl.matcher(response); if (!matcher.find()) { throw new BankException(res.getText(R.string.unable_to_find).toString() + " login url."); } String strLoginUrl="https://m.handelsbanken.se/primary/_-" + matcher.group(1); List<NameValuePair> postData=new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("username",username)); postData.add(new BasicNameValuePair("pin",password)); postData.add(new BasicNameValuePair("execute","true")); return new LoginPackage(urlopen,postData,response,strLoginUrl); }
Example 16
From project Android-DB-Editor, under directory /src/com/troido/dbeditor/.
Source file: ADBConnector.java

public static ArrayList<String> devices(){ String devices=runADBCommand(null,"devices"); ArrayList<String> deviceList=new ArrayList<String>(); String split[]=devices.split("\n"); Pattern p=Pattern.compile("(.*?)\\s*device$"); for ( String s : split) { Matcher m=p.matcher(s); if (m.find()) deviceList.add(m.group(1)); } return deviceList; }
Example 17
From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.
Source file: AddAccessRuleActivity.java

private static boolean validAddress(String address){ if (address != null && !address.trim().equals("")) { Pattern pattern=Pattern.compile("[a-zA-Z0-9.:/, ]+"); Matcher match=pattern.matcher(address); return match.matches(); } else { return false; } }
Example 18
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.
Source file: InternalUtils.java

/** * Remove xml and html tags, e.g. to safeguard against javascript injection attacks, or to get plain text for NLP. * @param xml can be null, in which case null will be returned * @return the text contents - ie input with all tags removed */ public static String stripTags(String xml){ if (xml == null) return null; if (xml.indexOf('<') == -1) return xml; Matcher m4=pScriptOrStyle.matcher(xml); xml=m4.replaceAll(""); Matcher m2=pComment.matcher(xml); String txt=m2.replaceAll(""); Matcher m=TAG_REGEX.matcher(txt); String txt2=m.replaceAll(""); Matcher m3=pDocType.matcher(txt2); String txt3=m3.replaceAll(""); return txt3; }
Example 19
From project android-xbmcremote, under directory /src/org/xbmc/android/util/.
Source file: SmsPopupUtils.java

private static String getEmailDisplayName(String displayString){ Matcher match=QUOTED_STRING_PATTERN.matcher(displayString); if (match.matches()) { return match.group(1); } return displayString; }
Example 20
From project androidannotations, under directory /AndroidAnnotations/androidannotations/src/main/java/com/googlecode/androidannotations/helper/.
Source file: RestAnnotationHelper.java

public List<String> extractUrlVariableNames(ExecutableElement element){ List<String> variableNames=new ArrayList<String>(); String uriTemplate=extractAnnotationValueParameter(element); boolean hasValueInAnnotation=uriTemplate != null; if (hasValueInAnnotation) { Matcher m=NAMES_PATTERN.matcher(uriTemplate); while (m.find()) { variableNames.add(m.group(1)); } } return variableNames; }
Example 21
From project androidquery, under directory /demo/src/com/androidquery/test/.
Source file: PatternUtility.java

public static String match(String html,String match){ Pattern p=Pattern.compile(match); Matcher m=p.matcher(html); if (m.find()) { return m.group(); } return null; }
Example 22
public static void writeIndented(String s){ s=s.trim(); Matcher m=WHITESPACE.matcher(s); s=m.replaceAll(NEWLINE); write(INDENT); write(s); write("\n"); }
Example 23
From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/.
Source file: AsYouTypeFormatter.java

private void narrowDownPossibleFormats(String leadingDigits){ int indexOfLeadingDigitsPattern=leadingDigits.length() - MIN_LEADING_DIGITS_LENGTH; Iterator<NumberFormat> it=possibleFormats.iterator(); while (it.hasNext()) { NumberFormat format=it.next(); if (format.leadingDigitsPatternSize() > indexOfLeadingDigitsPattern) { Pattern leadingDigitsPattern=regexCache.getPatternForRegex(format.getLeadingDigitsPattern(indexOfLeadingDigitsPattern)); Matcher m=leadingDigitsPattern.matcher(leadingDigits); if (!m.lookingAt()) { it.remove(); } } } }
Example 24
From project Aardvark, under directory /aardvark-interactive/src/test/java/gw/vark/.
Source file: InteractiveShellTest.java

@Test public void testNewProgramInstanceWhenAndOnlyWhenVarkFileIsRefreshed() throws Exception { Pattern pattern=Pattern.compile("show-startup-time show-startup-time: (\\d+) BUILD SUCCESSFUL.*"); writeToFile(_varkFile,VARK_FILE_0); writeToFile(_userClass,USER_CLASS_0); String read=writeToProcessAndRead("show-startup-time" + LINE_SEPARATOR).replace(LINE_SEPARATOR," "); assertThat(read).matches(pattern.pattern()); Matcher matcher=pattern.matcher(read); assertThat(matcher.matches()).isTrue(); long time=Long.parseLong(matcher.group(1)); read=writeToProcessAndRead("show-startup-time" + LINE_SEPARATOR).replace(LINE_SEPARATOR," "); assertThat(read).matches(pattern.pattern()); matcher=pattern.matcher(read); assertThat(matcher.matches()).isTrue(); long time2=Long.parseLong(matcher.group(1)); assertThat(time2).isEqualTo(time); writeToFile(_varkFile,VARK_FILE_1); read=writeToProcessAndRead("show-startup-time" + LINE_SEPARATOR).replace(LINE_SEPARATOR," "); assertThat(read).matches(pattern.pattern()); matcher=pattern.matcher(read); assertThat(matcher.matches()).isTrue(); time2=Long.parseLong(matcher.group(1)); assertThat(time2).isNotEqualTo(time); }
Example 25
From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.
Source file: EclipseConWizard.java

/** * Tries and find an encoding value on the very first line of the file contents. * @param fileContent The content from which to read an encoding value. * @return The charset name if it exists and is supported, <code>null</code> otherwise */ private static String getCharset(String fileContent){ String trimmedContent=fileContent.trim(); String charsetName=null; if (trimmedContent.length() > 0) { BufferedReader reader=new BufferedReader(new StringReader(trimmedContent)); String firstLine=trimmedContent; try { firstLine=reader.readLine(); } catch ( IOException e) { } Pattern encodingPattern=Pattern.compile("encoding\\s*=\\s*(\"|\')?([-a-zA-Z0-9]+)\1?"); Matcher matcher=encodingPattern.matcher(firstLine); if (matcher.find()) { charsetName=matcher.group(2); } } if (charsetName != null && Charset.isSupported(charsetName)) { return charsetName; } return null; }
Example 26
From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.
Source file: SGS.java

public void detectCharacterEncoding(){ HttpGet get; HttpResponse response; Header contentType; Pattern pattern; Matcher matcher; try { get=new HttpGet(baseUrl + homeAction); response=client.execute(get); contentType=response.getFirstHeader("Content-Type"); EntityUtils.consume(response.getEntity()); if (contentType == null || contentType.getValue() == null) { characterEncoding="ISO-8859-1"; } pattern=Pattern.compile(".*charset=(.+)"); matcher=pattern.matcher(contentType.getValue()); if (!matcher.matches()) { characterEncoding="ISO-8859-1"; } characterEncoding=matcher.group(1); } catch ( Exception e) { characterEncoding="ISO-8859-1"; } }
Example 27
From project activemq-apollo, under directory /apollo-broker/src/main/scala/org/apache/activemq/apollo/broker/jaxb/.
Source file: PropertiesReader.java

public String replaceSystemProperties(String str){ int start=0; while (true) { Matcher matcher=pattern.matcher(str); if (!matcher.find(start)) { break; } String property=System.getProperty(matcher.group(1)); if (property != null) { str=matcher.replaceFirst(property); } else { if (LOG.isDebugEnabled()) { LOG.debug("System property " + matcher.group(1) + " not found"); } start=matcher.end(); } } return str; }
Example 28
From project adbcj, under directory /postgresql/codec/src/main/java/org/adbcj/postgresql/codec/backend/.
Source file: BackendMessageDecoder.java

private CommandCompleteMessage decodeCommandComplete(DecoderInputStream input) throws IOException { Charset charset=connectionState.getBackendCharset(); String commandStr=input.readString(charset); Matcher matcher=COMMAND_PATTERN.matcher(commandStr); if (!matcher.matches()) { throw new IllegalStateException(String.format("Unable to parse command completion string '%s'",commandStr)); } Command command=Command.valueOf(matcher.group(1)); long count=-1; int oid=-1; if (matcher.group(3).length() > 0) { oid=Integer.valueOf(matcher.group(2)); count=Long.valueOf(matcher.group(3)); } else if (matcher.group(2).length() > 0) { count=Long.valueOf(matcher.group(2)); } return new CommandCompleteMessage(command,count,oid); }
Example 29
From project AdminCmd, under directory /src/main/java/be/Balor/Manager/.
Source file: LocaleManager.java

private String recursiveReplaceLocale(final String locale,final Map<String,String> values){ String ResultString=null; String result=locale; try { Matcher regexMatcher=recursiveLocale.matcher(locale); while (regexMatcher.find()) { ResultString=regexMatcher.group(1); final String recLocale=getLocale(ResultString); if (recLocale != null) { result=regexMatcher.replaceFirst(recLocale); } else { result=regexMatcher.replaceFirst(""); } regexMatcher=recursiveLocale.matcher(result); } regexMatcher=replaceLocale.matcher(result); while (regexMatcher.find()) { ResultString=regexMatcher.group(1); final String replaceValue=values.get(ResultString); if (replaceValue != null) { try { result=regexMatcher.replaceFirst(Matcher.quoteReplacement(replaceValue)); } catch ( final StringIndexOutOfBoundsException e) { result=regexMatcher.replaceFirst(replaceValue.replaceAll("\\W","")); } } else { result=regexMatcher.replaceFirst(""); } regexMatcher=replaceLocale.matcher(result); } } catch ( final PatternSyntaxException ex) { } final Matcher regexMatcher=buggedLocale.matcher(result); result=regexMatcher.replaceAll("?$1"); return result; }
Example 30
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.
Source file: DataManagement.java

private static String anonymiseNote(List<String> capitalisedWords,String note){ String[] alphabet={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; Pattern numeralPattern=Pattern.compile("[123456789]"); Pattern capitalWordsPattern=Pattern.compile("[A-Z][a-z0-9]+"); String newNote=note; Matcher capitalWordMatcher=capitalWordsPattern.matcher(note); Random randomGenerator=new Random(); while (capitalWordMatcher.find()) { int capitalWordIndex=randomGenerator.nextInt(capitalisedWords.size()); String capitalWord=capitalisedWords.get(capitalWordIndex); newNote=newNote.replace(capitalWordMatcher.group(),capitalWord); } Matcher numeralMatcher=numeralPattern.matcher(newNote); char[] keyChars=newNote.toCharArray(); while (numeralMatcher.find()) { int position=numeralMatcher.start(); keyChars[position]=alphabet[randomGenerator.nextInt(26)].charAt(0); } return String.valueOf(keyChars); }
Example 31
From project airlift, under directory /units/src/main/java/io/airlift/units/.
Source file: DataSize.java

public static DataSize valueOf(String size) throws IllegalArgumentException { Preconditions.checkNotNull(size,"size is null"); Preconditions.checkArgument(!size.isEmpty(),"size is empty"); Matcher matcher=PATTERN.matcher(size); if (!matcher.matches()) { throw new IllegalArgumentException("size is not a valid data size string: " + size); } double value=Double.parseDouble(matcher.group(1)); String unitString=matcher.group(2); for ( Unit unit : Unit.values()) { if (unit.getUnitString().equals(unitString)) { return new DataSize(value,unit); } } throw new IllegalArgumentException("Unknown unit: " + unitString); }
Example 32
From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/.
Source file: SelectPositionActivity.java

@Override protected String[] doInBackground(Double... params){ String[] result=new String[4]; try { List<Address> addr; if (!search) { addr=geo.getFromLocation(params[0],params[1],1); } else { String address=((TextView)findViewById(R.id.EditText_address_number)).getText().toString() + " " + ((TextView)findViewById(R.id.EditText_address_street)).getText().toString()+ " , "+ ((TextView)findViewById(R.id.EditText_address_town)).getText().toString(); addr=geo.getFromLocationName(address,1); if (addr.size() > 0) { geopoint=new GeoPoint((int)(addr.get(0).getLatitude() * 1E6),(int)(addr.get(0).getLongitude() * 1E6)); } } if (addr.size() > 0) { result[0]=addr.get(0).getAddressLine(0); result[3]=addr.get(0).getLocality(); result[2]=addr.get(0).getPostalCode(); Pattern p=Pattern.compile("^[\\d\\-]+"); Matcher m=p.matcher(result[0]); if (m.find()) { result[1]=m.group(); result[0]=result[0].replace(result[1],""); } } } catch ( IOException e) { Log.e(Constants.PROJECT_TAG,"Address error",e); } return result; }
Example 33
From project anadix, under directory /domains/anadix-html/src/main/java/org/anadix/html/.
Source file: Attributes.java

/** * Parses the style into list of key - value pairs * @param style String representation of style * @return list of key - value pairs */ public static Properties parseStyle(String style){ Properties result=new Properties(); style=style.replace("\r","").replace("\n","").replace("\t",""); Pattern p=Pattern.compile("[^:;]+:([^;\"]|\"[^\"]+\")*;?"); Matcher m=p.matcher(style); while (m.find()) { String prop=m.group().trim(); if (prop.endsWith(";")) { prop=prop.substring(0,prop.length() - 1); } String[] split=prop.split(":"); if (split.length < 2) { LoggerFactory.getLogger(Attributes.class).warn("CSS property without value: '{}'",prop); continue; } result.setProperty(split[0].trim(),split[1].trim()); } return result; }
Example 34
From project Android, under directory /AndroidNolesCore/src/util/.
Source file: SpreadsheetEntry.java

public static SpreadsheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth=parser.getDepth(); final SpreadsheetEntry entry=new SpreadsheetEntry(); parser.require(XmlPullParser.START_TAG,null,"entry"); while (parser.next() != XmlPullParser.END_DOCUMENT && parser.getDepth() > depth) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } final String name=parser.getName(); if ("updated".equals(name)) { entry.mUpdated=ParserUtils.readUpdated(parser); } else if ("title".equals(name)) { entry.put("title",ParserUtils.readTitle(parser)); } else if ("content".equals(name)) { final String text=ParserUtils.readText(parser); final Matcher matcher=getContentMatcher(text); while (matcher.find()) { final String key=matcher.group(1); final String value=matcher.group(2).trim(); entry.put(key,value); } } } return entry; }
Example 35
From project android-aac-enc, under directory /src/com/coremedia/iso/.
Source file: PropertyBoxParserImpl.java

public FourCcToBox invoke(){ String constructor; if (userType != null) { if (!"uuid".equals((type))) { throw new RuntimeException("we have a userType but no uuid box type. Something's wrong"); } constructor=mapping.getProperty((parent) + "-uuid[" + Hex.encodeHex(userType).toUpperCase()+ "]"); if (constructor == null) { constructor=mapping.getProperty("uuid[" + Hex.encodeHex(userType).toUpperCase() + "]"); } if (constructor == null) { constructor=mapping.getProperty("uuid"); } } else { constructor=mapping.getProperty((parent) + "-" + (type)); if (constructor == null) { constructor=mapping.getProperty((type)); } } if (constructor == null) { constructor=mapping.getProperty("default"); } if (constructor == null) { throw new RuntimeException("No box object found for " + type); } Matcher m=p.matcher(constructor); boolean matches=m.matches(); if (!matches) { throw new RuntimeException("Cannot work with that constructor: " + constructor); } clazzName=m.group(1); param=m.group(2).split(","); return this; }
Example 36
From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/provider/.
Source file: BooksProvider.java

private String keyFor(String name){ if (name == null) name=""; name=name.trim().toLowerCase(); if (mKeyPrefixes == null) { final Resources resources=getContext().getResources(); final String[] keyPrefixes=resources.getStringArray(R.array.prefixes); final int count=keyPrefixes.length; mKeyPrefixes=new Pattern[count]; for (int i=0; i < count; i++) { mKeyPrefixes[i]=Pattern.compile("^" + keyPrefixes[i] + "\\s+"); } } if (mKeySuffixes == null) { final Resources resources=getContext().getResources(); final String[] keySuffixes=resources.getStringArray(R.array.suffixes); final int count=keySuffixes.length; mKeySuffixes=new Pattern[count]; for (int i=0; i < count; i++) { mKeySuffixes[i]=Pattern.compile("\\s*" + keySuffixes[i] + "$"); } } final Pattern[] prefixes=mKeyPrefixes; for ( Pattern prefix : prefixes) { final Matcher matcher=prefix.matcher(name); if (matcher.find()) { name=name.substring(matcher.end()); break; } } final Pattern[] suffixes=mKeySuffixes; for ( Pattern suffix : suffixes) { final Matcher matcher=suffix.matcher(name); if (matcher.find()) { name=name.substring(0,matcher.start()); break; } } return name; }
Example 37
From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.
Source file: DeviceInfoSettings.java

private String getFormattedKernelVersion(){ String procVersionStr; try { BufferedReader reader=new BufferedReader(new FileReader("/proc/version"),256); try { procVersionStr=reader.readLine(); } finally { reader.close(); } final String PROC_VERSION_REGEX="\\w+\\s+" + "\\w+\\s+" + "([^\\s]+)\\s+"+ "\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+"+ "\\((?:[^(]*\\([^)]*\\))?[^)]*\\)\\s+"+ "([^\\s]+)\\s+"+ "(?:PREEMPT\\s+)?"+ "(.+)"; Pattern p=Pattern.compile(PROC_VERSION_REGEX); Matcher m=p.matcher(procVersionStr); if (!m.matches()) { Log.e(TAG,"Regex did not match on /proc/version: " + procVersionStr); return "Unavailable"; } else if (m.groupCount() < 4) { Log.e(TAG,"Regex match on /proc/version only returned " + m.groupCount() + " groups"); return "Unavailable"; } else { return (new StringBuilder(m.group(1)).append("\n").append(m.group(2)).append(" ").append(m.group(3)).append("\n").append(m.group(4))).toString(); } } catch ( IOException e) { Log.e(TAG,"IO Exception when getting kernel version for Device Info screen",e); return "Unavailable"; } }
Example 38
From project android_external_guava, under directory /src/com/google/common/base/.
Source file: Splitter.java

/** * Returns a splitter that considers any subsequence matching {@code pattern} to be a separator. For example, {@code Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a stringinto lines whether it uses DOS-style or UNIX-style line terminators. * @param separatorPattern the pattern that determines whether a subsequenceis a separator. This pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches theempty string */ public static Splitter on(final Pattern separatorPattern){ checkNotNull(separatorPattern); checkArgument(!separatorPattern.matcher("").matches(),"The pattern may not match the empty string: %s",separatorPattern); return new Splitter(new Strategy(){ public SplittingIterator iterator( final Splitter splitter, CharSequence toSplit){ final Matcher matcher=separatorPattern.matcher(toSplit); return new SplittingIterator(splitter,toSplit){ @Override public int separatorStart( int start){ return matcher.find(start) ? matcher.start() : -1; } @Override public int separatorEnd( int separatorPosition){ return matcher.end(); } } ; } } ); }