ycomp
ycomp

Reputation: 8583

How to restrict strings in XSD so they don't have leading or trailing whitespace?

I'm trying to do something very simple, but why is it so hard? I just want to disallow leading and trailing whitespace and leave everything else in the string intact (including middle whitespace)

  <xs:simpleType name="NonEmptyString"> 
    <xs:restriction base="xs:string">
      <xs:minLength value="1" />
      <xs:pattern value=".*[^\s].*"/> <!-- read my comments on sri's answer -->
    </xs:restriction>
  </xs:simpleType>

I am really super-stumped

none of these regexes will work for me either in my XSD or even in online regex testers (except some will work with the /g in a separate box on the online tester but I can't figure out how to get that to work in XSD)

I tried all of them from these pages, none would match:

Upvotes: 0

Views: 2733

Answers (1)

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

If by "leading and trailing spaces" you mean that neither the first character nor the last character (if any) of the string may be a blank (U+0020), then

[^ ](.*[^ ])?

should do fine. If the empty string should also be allowed, make the entire expression optional:

([^ ](.*[^ ])?)?

The first character class [^ ] matches a leading non-blank. The .* allows any sequence of characters after that initial character, ending with another non-blank. Since the set of strings with no leading or trailing spaces includes "a" and other single-character strings. the .* and the second character class expression are wrapped in parentheses and made optional.

If by "leading and trailing spaces" you mean "... whitespace", then the simplest thing would be to use \S', the complement of the whitespace escape\s`:

\S(.*\S)?

When using online regex testers, do bear in mind that there are many different notations for regular expressions, and XSD's pattern facets always try to match the entire input literal, so XSD regular expressions have no use for the ^ and $ anchors used in many other notations.

Upvotes: 3

Related Questions