CSS regex selector match one OR another condition?
You'll need to use two separate selectors with the same rule. CSS selectors don't really support alternation.
[class^='icon-'], [class*=' icon-'] {
/* ... */
}
div {
color: red;
}
[class^='icon-'], [class*=' icon-'] {
color: green;
}
<div class='icon-something another-class'>should match</div>
<div class='another-class icon-something'>should match</div>
<div class='another-icon-class another-class'>should not match</div>
Using regular expression in css?
You can manage selecting those elements without any form of regex as the previous answers show, but to answer the question directly, yes you can use a form of regex in selectors:
#sections div[id^='s'] {
color: red;
}
<div id="sections">
<div id="s1">one</div>
<div id="s2">two</div>
<div id="s3">three</div>
<div id="t1">four</div>
</div>
Differentiate XPath from CSS selectors (Regex?)
Regex is probably not the right tool for this job. Regular expressions can only analyze sentences that are Chomsky Type 3 grammar (regular grammar). I couldn't find anything related to that subject, but I don't think that XPath or css selectors are regular grammar, because they look too complex, and even if they were the regex would probably look awfully large and difficult to understand and maintain.
You should look for existing parsers, in whatever language you are using, to check if a given expression is valid. For instance in java there is the javax.xml.xpath.XPath
class that can parse XPath, and for css selectors I found this CSS Selector Parser.
Based on the four examples in your question I've built a simple proof of concept using the libraries that I mentioned:
import org.junit.Test;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import br.com.starcode.parccser.Parser;
import br.com.starcode.parccser.ParserException;
public class XPathAndCssTest extends org.junit.Assert {
@Test
public void testValidSelectors() {
assertTrue(isXPath("/bookstore/book[last()]"));
assertTrue(isCSSSelector("#some-id"));
assertTrue(isXPath("//title[@lang='en']"));
assertTrue(isCSSSelector(".someclass .someclass[disabled]"));
}
public boolean isCSSSelector(String selector) {
try {
Parser.parse(selector);
} catch (ParserException e) {
return false;
}
return true;
}
public boolean isXPath(String selector) {
try {
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.compile(selector);
} catch (XPathExpressionException e) {
return false;
}
return true;
}
}
In the isCSSSelector
and isXPath
methods, an expression is evaluated against a parser that throws and error if the expression is not valid. Instead of throwing the error I just return false. If everything goes right I return true.
In conclusion, to answer your question, yes, it is possible to programmatically differentiate a CSS from an XPath-Selector, as the code that I've posted proves that.
NOTE: This java code was built using maven with the following dependencies:
<dependency>
<groupId>br.com.starcode.parccser</groupId>
<artifactId>parccser</artifactId>
<version>1.1.3-RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
NOTE 2: In you question I noticed you were probably using javascript. A quick search on google showed up some examples of parsers in that language. For instance, js-xpath for XPath and scalpel for css selectors.
Add a CSS Class to an Element When A String Matches the Required Text - JavaScript
Try using includes.
if (termName[i].textContent.includes('Marketing')) {
menuItem.classList.add('active')
}
CSS selector to target element class or ID using only 1 statement
CSS spec requires attribute name to be set in attrib
attrib
: '[' S* [ namespace_prefix ]? IDENT S*
[ [ PREFIXMATCH |
SUFFIXMATCH |
SUBSTRINGMATCH |
'=' |
INCLUDES |
DASHMATCH ] S* [ IDENT | STRING ] S*
]? ']'
;
Take a look at the IDENT
that matches as follows:
ident [-]?{nmstart}{nmchar}*
nmstart [_a-z]|{nonascii}|{escape}
nonascii [^\0-\177]
escape {unicode}|\\[^\n\r\f0-9a-f]
unicode \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
nmchar [_a-z0-9-]|{nonascii}|{escape}
So you have to set an attribute name. It can`t be empty or asterisk (while its namespace can).
In summary: you can`t match ANY attribute (at least, CSS syntax doesn`t allow it).
How do I put a regular expression into a get statement in Cypress?
An alternative to a regex might be to use a partial attribute match
cy.get('[data-test-id^="table-element-"]) // ^= means starts-with "table-element-"
or
cy.get('[data-test-id^="table-element-"][data-test-id$="-cell"]) // also ends with "-cell"
This uses a regex inside a jQuery filter (but I'm sure there's an easier way)
cy.get('[data-test-id]')
.invoke('filter', function() {
const matches = [...this.attributes].filter(attr => {
attr.value.match(/table-element-[0-9]-[0-9]:[0-9]-cell/)
})
return matches
})
.should('have.length.gt', 0)
Python: using regex on a complicated list of multiple CSS selectors to extract their # and . tags
You don't need to loop over each line. And no need to escape the quotation marks in your regex:
import re
css='{\n\n"simpleSelectors": [\n\n"*",'
inputs = []
regexline = re.compile('"(.*)"')
matches = re.findall(regexline, css)
print( matches) # ['simpleSelectors', '*']
EDIT:
To subdivide your matches, use
matches = [item for match in re.findall(regexline, css) for item in match.split()]
Related Topics
Make Second Div Appear Above First, Without Absolute Position or Changing HTML
How Are Scrollbars in New Google Docs UI Styled (Esp. the Arrow Buttons)
Center Output (Plots) in the Notebook
Bind Angularjs Variables into CSS Syntax
Multiple !Important Class Declarations and Precedence
Vertical Scrollbar Leads to Horizontal Scrollbar
How to Alias Class Name in CSS or SASS
Image Mysteriously Ignoring Max-Width in Firefox & Ie
Are CSS Custom Properties Global Across Linked CSS Documents
Rtl Is on Web Page Reverses Numbers with a Dash
Twitter Bootstrap 3 How to Activate Navbar-Collapse on Small Devices
How to Define a Less Mixin to Generate a Transition-Property with a Variable Number of Parameters
CSS - Circle with Margin on Border
How to Align About the Colon in Each Line of Text Like Movie Credits Often Do
Background Images Path in SASS and Compass
Csp Style-Src: 'Unsafe-Inline' - Is It Worth It