Java Code Examples for com.helger.commons.string.StringHelper#replaceAll()

The following examples show how to use com.helger.commons.string.StringHelper#replaceAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObjectNameHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Create a clean property value applicable for an {@link ObjectName} property
 * value by replacing the special chars ":" and "," with "." and "//" with
 * "__". If the input value contains a blank, the quotes value is returned.
 *
 * @param sPropertyValue
 *        The original property value. May not be <code>null</code>.
 * @return The modified property value applicable for {@link ObjectName}.
 * @see ObjectName#quote(String)
 */
@Nonnull
public static String getCleanPropertyValue (@Nonnull final String sPropertyValue)
{
  // If a blank is contained, simply quote it
  if (sPropertyValue.indexOf (' ') != -1)
    return ObjectName.quote (sPropertyValue);

  // ":" is prohibited
  // "," is the property separator
  // "//" is according to the specs reserved for future use
  String ret = sPropertyValue;
  ret = StringHelper.replaceAll (ret, ':', '.');
  ret = StringHelper.replaceAll (ret, ',', '.');
  ret = StringHelper.replaceAll (ret, "//", "__");
  return ret;
}
 
Example 2
Source File: SVRLHelper.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
/**
 * Convert an "unsexy" location string in the for, of
 * <code>*:xx[namespace-uri()='yy']</code> to something more readable like
 * <code>prefix:xx</code> by using the mapping registered in the
 * {@link SVRLLocationBeautifierRegistry}.
 *
 * @param sLocation
 *        The original location string. May not be <code>null</code>.
 * @return The beautified string. Never <code>null</code>. Might be identical
 *         to the original string if the pattern was not found.
 * @since 5.0.1
 */
@Nonnull
public static String getBeautifiedLocation (@Nonnull final String sLocation)
{
  String sResult = sLocation;
  // Handle namespaces:
  // Search for "*:xx[namespace-uri()='yy']" where xx is the localname and yy
  // is the namespace URI
  final Matcher aMatcher = RegExHelper.getMatcher ("\\Q*:\\E([a-zA-Z0-9_]+)\\Q[namespace-uri()='\\E([^']+)\\Q']\\E",
                                                   sResult);
  while (aMatcher.find ())
  {
    final String sLocalName = aMatcher.group (1);
    final String sNamespaceURI = aMatcher.group (2);

    // Check if there is a known beautifier for this pair of namespace and
    // local name
    final String sBeautified = SVRLLocationBeautifierRegistry.getBeautifiedLocation (sNamespaceURI, sLocalName);
    if (sBeautified != null)
      sResult = StringHelper.replaceAll (sResult, aMatcher.group (), sBeautified);
  }
  return sResult;
}
 
Example 3
Source File: MainCreateEnumsGenericode22.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static String _getVarName (@Nonnull final String sOtherCol)
{
  String sVar = sOtherCol.substring (0, 1).toUpperCase (Locale.US) + sOtherCol.substring (1);
  sVar = StringHelper.replaceAll (sVar, '-', '_');
  return sVar;
}
 
Example 4
Source File: PDTFormatter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public LocalizedDateFormatCache ()
{
  super (aCacheKey -> {
    String sPattern = getSourcePattern (aCacheKey);

    // Change "year of era" to "year"
    sPattern = StringHelper.replaceAll (sPattern, 'y', 'u');

    if (false)
      if (aCacheKey.m_eMode == EDTFormatterMode.PARSE && StringHelper.getCharCount (sPattern, 'u') == 1)
      {
        // In Java 9, if CLDR mode is active, switch from a single "u" to
        // "uuuu" (for parsing)
        sPattern = StringHelper.replaceAll (sPattern, "u", "uuuu");
      }

    if (aCacheKey.m_eMode == EDTFormatterMode.PARSE &&
        "de".equals (aCacheKey.m_aLocale.getLanguage ()) &&
        aCacheKey.m_eStyle == FormatStyle.MEDIUM)
    {
      // Change from 2 required fields to 1
      sPattern = StringHelper.replaceAll (sPattern, "dd", "d");
      sPattern = StringHelper.replaceAll (sPattern, "MM", "M");
      sPattern = StringHelper.replaceAll (sPattern, "HH", "H");
      sPattern = StringHelper.replaceAll (sPattern, "mm", "m");
      sPattern = StringHelper.replaceAll (sPattern, "ss", "s");
    }

    // And finally create the cached DateTimeFormatter
    // Default to strict - can be changed afterwards
    return DateTimeFormatterCache.getDateTimeFormatterStrict (sPattern);
  }, 1000, LocalizedDateFormatCache.class.getName ());
}
 
Example 5
Source File: MainCreateEnumsGenericode23.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static String _getVarName (@Nonnull final String sOtherCol)
{
  String sVar = sOtherCol.substring (0, 1).toUpperCase (Locale.US) + sOtherCol.substring (1);
  sVar = StringHelper.replaceAll (sVar, '-', '_');
  return sVar;
}
 
Example 6
Source File: FilenameHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the passed filename into a valid filename by performing the
 * following actions:
 * <ol>
 * <li>Remove everything after a potential \0 character</li>
 * <li>Remove all characters that are invalid at the end of a file name</li>
 * <li>Replace all characters that are invalid inside a filename with a
 * underscore</li>
 * <li>If the filename is invalid on Windows platforms it is prefixed with an
 * underscore.</li>
 * </ol>
 * Note: this method does not handle Windows full path like
 * "c:\autoexec.bat"<br>
 *
 * @param sFilename
 *        The filename to be made value. May be <code>null</code>.
 * @return <code>null</code> if the input filename was <code>null</code> or if
 *         it consisted only of characters invalid for a filename; the
 *         potentially modified filename otherwise but <b>never</b> an empy
 *         string.
 * @see #getSecureFilename(String)
 */
@Nullable
@Nonempty
public static String getAsSecureValidFilename (@Nullable final String sFilename)
{
  // First secure it, by cutting everything behind the '\0'
  String ret = getSecureFilename (sFilename);

  // empty not allowed
  if (StringHelper.hasText (ret))
  {
    // Remove all trailing invalid suffixes
    while (ret.length () > 0 && StringHelper.endsWithAny (ret, ILLEGAL_SUFFIXES))
      ret = ret.substring (0, ret.length () - 1);

    // Replace all characters that are illegal inside a filename
    for (final char cIllegal : ILLEGAL_CHARACTERS)
      ret = StringHelper.replaceAll (ret, cIllegal, ILLEGAL_FILENAME_CHAR_REPLACEMENT);

    // Check if a file matches an illegal prefix
    final String sTempRet = ret;
    if (ArrayHelper.containsAny (ILLEGAL_PREFIXES, sTempRet::equalsIgnoreCase))
      ret = ILLEGAL_FILENAME_CHAR_REPLACEMENT + ret;

    // check if filename is prefixed with an illegal prefix
    // Note: we can use the default locale, since all fixed names are pure
    // ANSI names
    final String sUCFilename = ret.toUpperCase (SystemHelper.getSystemLocale ());
    if (ArrayHelper.containsAny (ILLEGAL_PREFIXES, x -> sUCFilename.startsWith (x + ".")))
      ret = ILLEGAL_FILENAME_CHAR_REPLACEMENT + ret;
  }

  // Avoid returning an empty string as valid file name
  return StringHelper.hasNoText (ret) ? null : ret;
}
 
Example 7
Source File: BenchmarkStringReplace.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public void run ()
{
  String s = "";
  for (int i = 0; i < m_nRuns; i++)
    s = StringHelper.replaceAll (SRC, RSRC, RDST);
  if (!s.equals (DST))
    throw new IllegalStateException (s);
}
 
Example 8
Source File: MainCreateEnumsGenericode21.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static String _getVarName (@Nonnull final String sOtherCol)
{
  String sVar = sOtherCol.substring (0, 1).toUpperCase (Locale.US) + sOtherCol.substring (1);
  sVar = StringHelper.replaceAll (sVar, '-', '_');
  return sVar;
}
 
Example 9
Source File: MainCreateJAXBBinding23.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String _convertToPackage (@Nonnull final String sNamespaceURI)
{
  // Lowercase everything
  String s = sNamespaceURI.toLowerCase (Locale.US);

  String [] aParts;
  final URL aURL = URLHelper.getAsURL (sNamespaceURI);
  if (aURL != null)
  {
    // Host
    String sHost = aURL.getHost ();

    // Kick static prefix: www.helger.com -> helger.com
    sHost = StringHelper.trimStart (sHost, "www.");

    // Reverse domain: helger.com -> com.helger
    final List <String> x = CollectionHelper.getReverseList (StringHelper.getExploded ('.', sHost));

    // Path in regular order:
    final String sPath = StringHelper.trimStart (aURL.getPath (), '/');
    x.addAll (StringHelper.getExploded ('/', sPath));

    // Convert to array
    aParts = ArrayHelper.newArray (x, String.class);
  }
  else
  {
    // Kick known prefixes
    for (final String sPrefix : new String [] { "urn:", "http://" })
      if (s.startsWith (sPrefix))
      {
        s = s.substring (sPrefix.length ());
        break;
      }

    // Replace all illegal characters
    s = StringHelper.replaceAll (s, ':', '.');
    s = StringHelper.replaceAll (s, '-', '_');
    aParts = StringHelper.getExplodedArray ('.', s);
  }

  // Split into pieces and replace all illegal package parts (e.g. only
  // numeric) with valid ones
  for (int i = 0; i < aParts.length; ++i)
    aParts[i] = RegExHelper.getAsIdentifier (aParts[i]);

  return StringHelper.getImploded (".", aParts);
}
 
Example 10
Source File: MainCreateJAXBBinding20.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String _convertToPackage (@Nonnull final String sNamespaceURI)
{
  // Lowercase everything
  String s = sNamespaceURI.toLowerCase (Locale.US);

  String [] aParts;
  final URL aURL = URLHelper.getAsURL (sNamespaceURI);
  if (aURL != null)
  {
    // Host
    String sHost = aURL.getHost ();

    // Kick static prefix: www.helger.com -> helger.com
    sHost = StringHelper.trimStart (sHost, "www.");

    // Reverse domain: helger.com -> com.helger
    final ICommonsList <String> x = StringHelper.getExploded ('.', sHost);
    x.reverse ();

    // Path in regular order:
    final String sPath = StringHelper.trimStart (aURL.getPath (), '/');
    x.addAll (StringHelper.getExploded ('/', sPath));

    // Convert to array
    aParts = ArrayHelper.newArray (x, String.class);
  }
  else
  {
    // Kick known prefixes
    for (final String sPrefix : new String [] { "urn:", "http://" })
      if (s.startsWith (sPrefix))
      {
        s = s.substring (sPrefix.length ());
        break;
      }

    // Replace all illegal characters
    s = StringHelper.replaceAll (s, ':', '.');
    s = StringHelper.replaceAll (s, '-', '_');
    aParts = StringHelper.getExplodedArray ('.', s);
  }

  // Split into pieces and replace all illegal package parts (e.g. only
  // numeric) with valid ones
  for (int i = 0; i < aParts.length; ++i)
    aParts[i] = RegExHelper.getAsIdentifier (aParts[i]);

  return StringHelper.getImploded (".", aParts);
}
 
Example 11
Source File: MainCreateJAXBBinding21.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String _convertToPackage (@Nonnull final String sNamespaceURI)
{
  // Lowercase everything
  String s = sNamespaceURI.toLowerCase (Locale.US);

  String [] aParts;
  final URL aURL = URLHelper.getAsURL (sNamespaceURI);
  if (aURL != null)
  {
    // Host
    String sHost = aURL.getHost ();

    // Kick static prefix: www.helger.com -> helger.com
    sHost = StringHelper.trimStart (sHost, "www.");

    // Reverse domain: helger.com -> com.helger
    final List <String> x = CollectionHelper.getReverseList (StringHelper.getExploded ('.', sHost));

    // Path in regular order:
    final String sPath = StringHelper.trimStart (aURL.getPath (), '/');
    x.addAll (StringHelper.getExploded ('/', sPath));

    // Convert to array
    aParts = ArrayHelper.newArray (x, String.class);
  }
  else
  {
    // Kick known prefixes
    for (final String sPrefix : new String [] { "urn:", "http://" })
      if (s.startsWith (sPrefix))
      {
        s = s.substring (sPrefix.length ());
        break;
      }

    // Replace all illegal characters
    s = StringHelper.replaceAll (s, ':', '.');
    s = StringHelper.replaceAll (s, '-', '_');
    aParts = StringHelper.getExplodedArray ('.', s);
  }

  // Split into pieces and replace all illegal package parts (e.g. only
  // numeric) with valid ones
  for (int i = 0; i < aParts.length; ++i)
    aParts[i] = RegExHelper.getAsIdentifier (aParts[i]);

  return StringHelper.getImploded (".", aParts);
}
 
Example 12
Source File: MainCreateJAXBBinding22.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String _convertToPackage (@Nonnull final String sNamespaceURI)
{
  // Lowercase everything
  String s = sNamespaceURI.toLowerCase (Locale.US);

  String [] aParts;
  final URL aURL = URLHelper.getAsURL (sNamespaceURI);
  if (aURL != null)
  {
    // Host
    String sHost = aURL.getHost ();

    // Kick static prefix: www.helger.com -> helger.com
    sHost = StringHelper.trimStart (sHost, "www.");

    // Reverse domain: helger.com -> com.helger
    final List <String> x = CollectionHelper.getReverseList (StringHelper.getExploded ('.', sHost));

    // Path in regular order:
    final String sPath = StringHelper.trimStart (aURL.getPath (), '/');
    x.addAll (StringHelper.getExploded ('/', sPath));

    // Convert to array
    aParts = ArrayHelper.newArray (x, String.class);
  }
  else
  {
    // Kick known prefixes
    for (final String sPrefix : new String [] { "urn:", "http://" })
      if (s.startsWith (sPrefix))
      {
        s = s.substring (sPrefix.length ());
        break;
      }

    // Replace all illegal characters
    s = StringHelper.replaceAll (s, ':', '.');
    s = StringHelper.replaceAll (s, '-', '_');
    aParts = StringHelper.getExplodedArray ('.', s);
  }

  // Split into pieces and replace all illegal package parts (e.g. only
  // numeric) with valid ones
  for (int i = 0; i < aParts.length; ++i)
    aParts[i] = RegExHelper.getAsIdentifier (aParts[i]);

  return StringHelper.getImploded (".", aParts);
}
 
Example 13
Source File: CollatorHelper.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
public CollatorCache ()
{
  super (aLocale -> {
    if (aLocale == null)
    {
      LOGGER.error ("Very weird: no locale passed in. Falling back to system locale.");
      return Collator.getInstance (SystemHelper.getSystemLocale ());
    }

    // Collator.getInstance is synchronized and therefore extremely slow ->
    // that's why we put a cache around it!
    final Collator aCollator = Collator.getInstance (aLocale);
    if (!(aCollator instanceof RuleBasedCollator))
    {
      LOGGER.warn ("Collator.getInstance did not return a RulleBasedCollator but a " +
                   aCollator.getClass ().getName ());
      return aCollator;
    }

    try
    {
      final String sRules = ((RuleBasedCollator) aCollator).getRules ();
      if (!sRules.contains ("<'.'<"))
      {
        // Nothing to replace - use collator as it is
        LOGGER.warn ("Failed to identify the Collator rule part to be replaced. Locale used: " + aLocale);
        return aCollator;
      }

      final String sNewRules = StringHelper.replaceAll (sRules, "<'.'<", "<' '<'.'<");
      final RuleBasedCollator aNewCollator = new RuleBasedCollator (sNewRules);
      aNewCollator.setStrength (Collator.TERTIARY);
      aNewCollator.setDecomposition (Collator.FULL_DECOMPOSITION);
      return aNewCollator;
    }
    catch (final ParseException ex)
    {
      throw new IllegalStateException ("Failed to parse collator rule set for locale " + aLocale, ex);
    }
  }, 500, CollatorHelper.class.getName ());
}
 
Example 14
Source File: ErrorTextProvider.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
public String getFormattedText (@Nonnull final String sReplacement)
{
  return StringHelper.replaceAll (m_sText, PLACEHOLDER_STR, sReplacement);
}
 
Example 15
Source File: CSSExpression.java    From ph-css with Apache License 2.0 3 votes vote down vote up
/**
 * Get a quoted string value. Every double quote (") is replaced to a
 * backslash and a double quote (\").
 *
 * @param sValue
 *        The source value. May not be <code>null</code>.
 * @return An opening double quote + the quoted string + a closing double
 *         quote
 * @since 6.1.2
 */
@Nonnull
@Nonempty
public static String getQuotedStringValue (@Nonnull final String sValue)
{
  ValueEnforcer.notNull (sValue, "Value");
  if (sValue.length () == 0)
    return "\"\"";
  return '"' + StringHelper.replaceAll (sValue, "\"", "\\\"") + '"';
}
 
Example 16
Source File: FilenameHelper.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Ensure that the passed path is using the Windows style separator "\"
 * instead of the Operating System dependent one.
 *
 * @param sAbsoluteFilename
 *        The file name to use. May be <code>null</code>
 * @return <code>null</code> if the passed path is <code>null</code>.
 * @see #getPathUsingWindowsSeparator(File)
 */
@Nullable
public static String getPathUsingWindowsSeparator (@Nullable final String sAbsoluteFilename)
{
  return sAbsoluteFilename == null ? null
                                   : StringHelper.replaceAll (sAbsoluteFilename, UNIX_SEPARATOR, WINDOWS_SEPARATOR);
}
 
Example 17
Source File: FilenameHelper.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Ensure that the passed path is using the Unix style separator "/" instead
 * of the Operating System dependent one.
 *
 * @param sAbsoluteFilename
 *        The file name to use. May be <code>null</code>
 * @return <code>null</code> if the passed path is <code>null</code>.
 * @see #getPathUsingUnixSeparator(File)
 */
@Nullable
public static String getPathUsingUnixSeparator (@Nullable final String sAbsoluteFilename)
{
  return sAbsoluteFilename == null ? null
                                   : StringHelper.replaceAll (sAbsoluteFilename, WINDOWS_SEPARATOR, UNIX_SEPARATOR);
}
 
Example 18
Source File: ClassHelper.java    From ph-commons with Apache License 2.0 2 votes vote down vote up
/**
 * Get the path representation of the passed class name. The path
 * representation is achieved by replacing all dots (.) with forward slashes
 * (/) in the class name.
 *
 * @param sClassName
 *        The class name of which the path is to be retrieved. May be
 *        <code>null</code>.
 * @return The path representation
 */
@Nullable
public static String getPathFromClass (@Nullable final String sClassName)
{
  return sClassName == null ? null : StringHelper.replaceAll (sClassName, '.', '/');
}