All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitlab.mvysny.konsumexml.Whitespace.kt Maven / Gradle / Ivy

The newest version!
package com.gitlab.mvysny.konsumexml

private val WHITESPACE_REGEX = Regex("\\s")
private val WHITESPACES_REGEX = Regex("\\s+")

/**
 * Processes the whitespaces in XML. Please see [XML Whitespaces](https://www.w3schools.com/xml/schema_facets.asp)
 * for more details.
 * @author mavi
 */
public interface Whitespace {
    /**
     * Processes given [text] and returns the text that should be reported to the client.
     */
    public fun process(text: String): String

    public companion object {
        /**
         * Preserves all whitespaces as-is - will not remove any whitespaces, nor will perform any conversion
         * (e.g. from tabs to spaces).
         */
        public val preserve: Whitespace = object : Whitespace {
            override fun process(text: String): String = text
        }

        /**
         * This will replace all white space characters (line feeds, tabs, spaces, and carriage returns) with spaces,
         * however it will not collapse consecutive whitespaces.
         */
        public val replace: Whitespace = object : Whitespace {
            override fun process(text: String): String =
                    text.replace(WHITESPACE_REGEX, " ")
        }

        /**
         * This will collapse all white space characters, and remove leading/trailing whitespaces:
         *
         * * line feeds, tabs, spaces, carriage returns are replaced with spaces,
         * * multiple whitespace characters are reduced to a single space,
         *
         * The difference between this one and [collapse] is that even though the
         * leading and trailing whitespaces are collapsed to a single space, they are not removed completely.
         * This is useful when parsing mixed contents. See [Konsumer.textRecursively] for more details.
         */
        public val collapse_no_trim: Whitespace = object : Whitespace {
            override fun process(text: String): String =
                    text.replace(WHITESPACES_REGEX, " ")
        }

        /**
         * This will collapse all white space characters, and remove leading/trailing whitespaces:
         *
         * * line feeds, tabs, spaces, carriage returns are replaced with spaces,
         * * multiple whitespace characters are reduced to a single space,
         * * leading and trailing whitespaces are removed completely.
         */
        public val collapse: Whitespace = object : Whitespace {
            override fun process(text: String): String =
                    text.replace(WHITESPACES_REGEX, " ").trim()
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy