Menu
  • HOME
  • TAGS

Xml schema regex to not allow white spaces alone

Tag: regex,xml,xsd

In xml, i have a tag say <membercode>

The regex pattern for the field currently is <xs:pattern value="[a-zA-Z0-9\s]{1,3}" />

The membercode must accept values as follows:

1) "XY"  -> pass

2) "XY " -> pass

3) "   " -> i need to have this failed. but it is getting passed.

4) " XY " -> need to be failed 

EDIT: Requirements:

1) total allowed characters must be maximum 3.

2) With in the allowed 3 chars, there can be spaces. ex: "XY", "XY "," XY" , "X "

3) But if the total chars exceed 3 or if there is only spaces(no alphanumeric chars) then it should not be allowed.

tried whitespace collapse property, but in that case the maxlength is applied after the collapse is done. so values more than max length is also allowed.

hence tried below things..

<xs:pattern value="[a-zA-Z0-9]{1,3}[\s?]" />
<xs:pattern value="[a-zA-Z0-9]{1,3}|[a-zA-Z0-9\s?]{1,3}" />

but couldn't get hold on the correct solution.

Please point me the correct approach for this..

Many thanks for the suggestions!

Best How To :

You're on the right track using <xs:whiteSpace> restriction, but the value should be preserve in order to not modify the original whitespace.

You can use this pattern:

[\w\d ]*[\w\d][\w\d ]*

The central part ([\w\d]) says that a letter or a digit must appear. Before and after that compulsory alphanumeric character, the string can optionally have any letter/digit/space combination ([\w\d ]*). The restrictions <xs:whiteSpace> and <xs:maxLength> ensure that there is no more than 3 length strings including original white-spaces.

<xs:element name="elem">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:whiteSpace value="preserve"/>
            <xs:maxLength value="3"/>
            <xs:pattern value="[\w\d ]*[\w\d][\w\d ]*"></xs:pattern>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

Note that you can change \w to a-zA-Z if you don't want the underscore character that is also included in \w.

Get XML node value when previous node value conditions are true (without looping)

xml,vb.net,linq-to-xml

UPDATE Using an XDocument vs an XmlDocument, I believe this does what you're asking without using loops. This is dependent on the elements being in the order of <PhoneType> <PhonePrimaryYN> <PhoneNumber> string xml = "<?xml version=\"1.0\"?>" + "<Root>" + " <PhoneType dataType=\"string\">" + " <Value>CELL</Value>" + " </PhoneType>" + "...

Store regex pattern as a string in PHP when regex pattern contains both single and double quotes

php,regex

The quotes are an issue but not the issue you are running into when you escape them. Your delimiter is terminating your regex just before the closing a which is giving you the unknown modifier error. It appears you don't have error reporting on though so you aren't seeing that....

Regex not working in HTML5 pattern

regex,html5

The pattern attribute has to match the entire string. Assertions check for a match, but do not count towards the total match length. Changing the second assertion to \w+ will make the pattern match the entire string. You can also skip the implied ^, leaving you with just: <input pattern="(?!34)\w+"...

Does there exist an algorithm for iterating through all strings that conform to a particular regex?

c#,regex,algorithm

Let's say the domain is as following String domain[] = { a, b, .., z, A, B, .. Z, 0, 1, 2, .. 9 }; Let's say the password size is 8 ArrayList allCombinations = getAllPossibleStrings2(domain,8); This is going to generate SIZE(domain) * LENGTH number of combinations, which is in...

Collect strings after a foreach loop

c#,xml,foreach

Yep, you need to do the adding within the loop. I'd use a List<string> as it supports LINQ: XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); List<string> skills = new List<string>(); foreach (XmlNode skillNameNode in skillNameNodeList) { skills.Add(skillNameNode.Attributes["value"].Value); } ...

match line break except line begin with spcific word or blank line

regex,notepad++

Try this regex: (?<=[a-zA-Z])(\n) I used parentheses to capture the newline character. https://regex101.com/r/zS9pB4/3...

odoo v8 - Field(s) `arch` failed against a constraint: Invalid view definition

python,xml,view,odoo,add-on

You have made silly mistake in defining _columns. _colums is not valid dictionary name for fields structure. Replace this by _columns and restart service and update module. ...

XSLT How to remove style from div and td tags

xml,xslt

To remove some nodes start with the identity transformation template <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> then add an empty template for the nodes to be removed: <xsl:template xmlns:xhtml="http://www.w3.org/1999/xhtml" match="xhtml:div/@style | xhtml:li/@style | xhtml:td/@style | xhtml:span/@style"/> ...

Finding embeded xpaths in a String

java,regex

Use {} instead of () because {} are not used in XPath expressions and therefore you will not have confusions.

xpath query seem to be failing

xml,xpath

$str = '<root><Pages> <copyright>me inc. 2015,</copyright> <author>Me</author> <lastUpdate>2/1/1999</lastUpdate> <Home>--------------------</Home> <About>--------------------</About> <Contact>------------------</Contact> </Pages></root>'; $xml = simplexml_load_string($str); $result = $xml->xpath('//Pages/*[(name() = "Home") or following-sibling::Home]'); if ($result === false) { $this->parseError(); //To return xml Error code...

How to create the javascript regular expression for number with some special symbols

javascript,regex

This matches all given examples as well: ^\$?\d+(?:[.,:]\d+)?%?$ See it in action: RegEx101 Please comment, if adjustment / further detail is required....

Validate part of mail suffix

c#,regex

You can use this regex to test. It will ensure that after the @ there is .xx. but may also match the string @.xx.* .*@[^.]*[.]xx[.] Or this one to ensure that there is at least one character before and after the @. [email protected][^.]+[.]xx[.] ...

REGEX python find previous string

python,regex,string

Updated: This will check for the existence of a sentence followed by special characters. It returns false if there are no special characters, and your original sentence is in capture group 1. Updated Regex101 Example r"(.*[\w])([^\w]+)" Alternatively (without a second capture group): Regex101 Example - no second capture group r"(.*[\w])(?:[^\w]+)"...

Load XML to list using LINQ [duplicate]

c#,xml,linq

Make a base class which will have id,x,y,z, and have Vendors,Bankers and Hospitals extend it. Then you can have a collection of the base class, and add to it the classes that inherit from it....

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

Fixed element in android?

android,xml,android-fragments

You need a FrameLayout. In a FrameLayout, the children are overlapped on top of each other with the last child being at the topmost. activity_main.xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:fab="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"...

Convert contents of an XmlNodeList to a new XmlDocument without looping

c#,xml,xpath,xmldocument,xmlnodelist

If you're happy to convert it into LINQ to XML, it's really simple: XDocument original = ...; // However you load the original document // Separated out for clarity - could be inlined, of course string xpath = "//Person[not(PersonID = following::Person/PersonID)]" XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpath) )...

Tagging values in HTML document for automated extraction

html,xml,html5

If you are using them as meta-documents and they are sent to the parser, then converted as HTML and as long as the converted HTMLs do not have any irrelevant tags, it is fine! So, if the following code: <requirement> THE REQUIREMENT HERE </requirement> Gets converted into something like: <!--...

Reg ex matching a word

regex

You could use a negative lookahead which will exclude those having _FX following the initial alpha string ^ABD_DEF_GHIJ(?!_FX)(?:_\d{8})?$ see example here...

List view not returning to original state after clearing search

java,android,xml,android-activity,android-listfragment

You are operating on the original data instead of filtered data. You should maintain a reference to original data and use the filtered data for all other purposes. So that the original data is displayed when search is cleared. Replace all usages of mData with mFilteredData as below and only...

XSL transformation outputting multiple times and other confusion

xml,xslt,xpath

1) Your template is applied to 3 elements, and for each of them, loops over all the parents li elements (yes, for each of them, ask all the li elements, children of the grand-father of the current content, which are all the 3 li elements, each time). 2) Because that's...

How many characters are visible like a space, but are not space characters?

php,regex

You can make use of a Unicode category \p{Zs}: Zs    Space separator $string = preg_replace('~\p{Zs}~u', ' ', $string); The \p{Zs} Unicode category class will match these space-like symbols: Character Name U+0020 SPACE U+00A0 NO-BREAK SPACE U+1680 OGHAM SPACE MARK U+2000 EN QUAD U+2001 EM QUAD U+2002 EN SPACE U+2003 EM SPACE...

MySQL substring match using regular expression; substring contain 'man' not 'woman'

mysql,regex

A variant of n-dru pattern since you don't need to describe all the string: SELECT '#hellowomanclothing' REGEXP '(^#.|[^o]|[^w]o)man'; Note: if a tag contains 'man' and 'woman' this pattern will return 1. If you don't want that Gordon Linoff solution is what you are looking for....

Swing regular expression for phone number validation

java,regex

To only allow digits, comma and spaces, you need to remove (, ) and -. Here is a way to do it with Matcher.find(): Pattern pattern = Pattern.compile("^[0-9, ]+$"); ... if (!m.find()) { evt.consume(); } And to allow an empty string, replace + with *: Pattern pattern = Pattern.compile("^[0-9, ]*$");...

Python regular expression, matching the last word

python,regex,list

Use the alternation with $: import re mystr = 'HelloWorldToYou' pat = re.compile(r'([A-Z][a-z]*)') # or your version with `.*?`: pat = re.compile(r'([A-Z].*?)(?=[A-Z]+|$)') print pat.findall(mystr) See IDEONE demo Output: ['Hello', 'World', 'To', 'You'] Regex explanation: ([A-Z][a-z]*) - A capturing group that matches [A-Z] a capital English letter followed by [a-z]* -...

regex - Match filename with or without extension

regex,logstash-grok

This is about as simple as I can get it: \b\w+\.?\w* See demo...

Please can someone help me understand the exec method for regular expressions?

javascript,regex

I don't understand why it would give me two hellos back? Because the first entry in the array is the overall match for the expression, which is then followed by the content of any capture groups the expression defines. Since the expression defines one capture group, you get back...

Get number from string

regex

Use \d+ to match one or more digits. \b(?:http:\/\/)?(?:www\.)?example\.com\/g\/(\d+)\/\w put http:// and www. inside a capturing or non-caturing group and then make it as optional by adding ? quantifier next to that group. For both http and https, it would be (?:https?:\/\/)? DEMO...

Regex pass dynamic values with boundry

c#,regex,string,boundary

Your first regular expression has a black slash followed by the letter b because of that @. The second one has the character that represents backspace. Just put an @ in front string bound = @"\b"; ...

Regex that allow void fractional part of number

c#,regex

Just get the dot outside of the captruing group and then make it as optional. @"[+-]?\d+\.?\d*" Use anchors if necessary. @"^[+-]?\d+\.?\d*$" ...

Regular Expression for whole world

regex,c#-4.0,vb6

You can use: Public\s+Const\s+g(?<Name>[a-zA-Z][a-zA-Z0-9]*)\s+=\s+(?<Value>False|True) demo ...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

How to calculate max string-length of a node-set?

xml,xslt,xslt-1.0,libxslt

<xsl:variable name="max_a_width"> <xsl:for-each select="data"> <xsl:sort select="string-length(@a)" data-type="number" /> <xsl:if test="position() = last()"> <xsl:value-of select="string-length(@a)" /> </xsl:if> </xsl:for-each> </xsl:variable> This is the general method of picking from an ordered list of derived values in XSLT 1.0. If you want to pick the minimum/maximum from actual (natively sortable) values, you can take...

Match a pattern preceded by a specific pattern without using a lookbehind

regex,eclipse,lookahead

A work-around for the lack of variable-length lookbehind is available in situations when your strings have a relatively small fixed upper limit on their length. For example, if you know that strings are at most 100 characters long, you could use {0,100} in place of * or {1,100} in place...

Error when building an XDocument

c#,xml,linq,xpath,linq-to-xml

You can ignore pretty much all your code, the issue is just this: XDocument people = new XDocument("Persons"); You can't create an XDocument containing a string, you need to add an element: XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpathFilterDups))); ...

Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime

What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...

XSLT for-each statement not iterating proper amount of times

xml,xslt

Try it this way? <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/template/L"> <html> <body> <ul> <xsl:for-each select="Q"> <li> <xsl:value-of select="text()"/> <ul> <xsl:for-each select="R"> <li> <xsl:value-of select="."/> </li> </xsl:for-each> </ul> </li> </xsl:for-each> </ul> </body> </html> </xsl:template> </xsl:stylesheet> Explanation: When...

XElement.Value is stripping XML tags from content

c#,.net,xml,xml-parsing,xelement

As others have said, this format is truly horrible, and will break as soon as the XML embedded in the JSON will contain double quotes (because in the JSON they will be encoded as \", which will make the XML invalid). The JSON should really be embedded as CDATA. Now,...

Get all prices with $ from string into an array in Javascript

javascript,regex,currency

It’s quite trivial: RegEx string.match(/\$((?:\d|\,)*\.?\d+)/g) || [] That || [] is for no matches: it gives an empty array rather than null. Matches $99 $.99 $9.99 $9,999 $9,999.99 Explanation / # Start RegEx \$ # $ (dollar sign) ( # Capturing group (this is what you’re looking for) (?: #...

Warning: preg_match_all(): Unknown modifier '\' [duplicate]

php,regex,warnings

Use a different set of delimiters for the regex. For example, you can write preg_match_all('~[^/\s]+/\S+\.(jpg|png|gif)~', $string, $results ...

Extracting strings from HTML with Python wont work with regex or BeautifulSoup

python,regex,parsing,beautifulsoup,python-requests

In order to match the string with a literal backlash, you need to double-escape it in a raw string, e.g.: re.search(r'@CAD_DTA\\">(.+?)@[email protected]@CAD_LBL',result.text) ^ ^ In order to get the index of the found match, you can use start([group]) of re.MatchObject IDEONE demo: import re obj = re.search(r'@CAD_DTA\\">(.+?)@[email protected]@CAD_LBL', 'Some text [email protected]_DTA\\">I WANT...

How to write RegEx for inserting line break for line length more than 30 characters?

regex

Find what: ^(.{30}) Replace with: \1\n ...

Ruby- get a xml node value

ruby,xml

Try to use css instead of xpath, this will work for you, doc = Nokogiri::XML(response.body) values = doc.css('Name').select{|name| name.text}.join',' puts values => Ram,Sam ...

Parsing XML array using Jquery

javascript,jquery,xml,jquery-mobile

EMI and CustomerName are elements under json so you can use .find() to find those elements and then text() to get its value. $(data).find("json").each(function (i, item) { var heures = $(item).find("CustomerName").text(); var nbr = $(item).find("EMI").text(); console.log(heures); }); .attr() is used to get the attribute value of an element like in...

About sorting based on the counting of subelements

xml,xslt

You can use a key in order to count the properties in the sort instruction. A stylesheet containing the following: <xsl:key name="p" match="property" use="@agency"/> <xsl:template match="/immo"> <result> <xsl:for-each select="agency"> <xsl:sort select="count(key('p', @name))"/> <res id="{ @name }" count="{ count(key('p', @name)) }"/> </xsl:for-each> </result> </xsl:template> when applied to the following input: <immo>...

How to Match a string with the format: “20959WC-01” in php?

php,regex

$pattern = '! ^ # start of string \d{5} # five digits [[:alpha:]]{2} # followed by two letters - # followed by a dash \d{2} # followed by two digits $ # end of string !x'; $matches = preg_match($pattern, $input); ...

Regex with whitespaces and preceding zeros

regex,sas

You can use this simplified regex: /^[\s0]*11\s*$/ ...

type conversion performance optimizable?

c#,xml,csv,optimization,type-conversion

IEnumerable<string> values = new List<string>(); values = … Probably not going to be a big deal, but why create a new List<string>() just to throw it away. Replace this with either: IEnumerable<string> values; values = … If you need values defined in a previous scope, or else just: Enumerable<string> values...

C# XML: System.InvalidOperationException

c#,xml

Is "User Info" and "Course Data" is a different entity. If it is so, I think you may encapsulate them in one entity. XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("My Entity"); /* It is a biggest one*/ writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor...

How to match words in 2 list against another string of words without sub-string matching in Python?

python,regex,string,loops,twitter

Store slangNames and riskNames as sets, split the strings and check if any of the words appear in both sets slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"]) riskNames = set(["enough", "pop", "final", "stress", "trade"]) d = {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"} for...