Regular Expression To Match String Not Starting With Or Ending With Spaces

前端 未结 2 1591
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 00:37

I need a regular expression that makes sure a string does not start with or end with a space. I don\'t care if it has a space in the \"middle\" just not at the beginning or the

相关标签:
2条回答
  • 2021-01-23 01:17

    You use lookaround assertions, because they're zero-width:

    ^(?=\S).*(?<=\S)$
    

    It might be better to use negative assertions and positive character classes, though:

    ^(?!\s).*(?<=\s)$
    
    0 讨论(0)
  • 2021-01-23 01:19

    You could do this:

    ^\S(.*\S)?$
    

    It will match either a single non space character, followed by an optional zero-or-more characters followed by a single non space character.


    Update

    Given that you said this was for XML schema validation I tested it with this schema:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="xml">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="test" minOccurs="0" maxOccurs="unbounded">
              <xs:complexType>
                <xs:attribute name="value">
                  <xs:simpleType>
                    <xs:restriction base="xs:string">
                      <xs:pattern value="\S(.*\S)?"/>
                    </xs:restriction>
                  </xs:simpleType>
                </xs:attribute>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    

    Against this sample document

    <xml>
      <test value="HELLO"/>    <!-- MATCH -->
      <test value="HEL LO"/>   <!-- MATCH -->
      <test value="HELLO "/>   <!-- ERROR -->
      <test value=" HELLO"/>   <!-- ERROR -->
      <test value="H"/>        <!-- MATCH -->
    </xml>
    

    So it appears that if you simply remove the start / end brackets. It works.

    0 讨论(0)
提交回复
热议问题