[英]Java regex to replace whitespaces in css class string with dots
Given a class
attribute of an HTML element, I want to generate a String suitable for css selector. 给定一个HTML元素的class
属性,我想生成一个适合CSS选择器的String。
For instance, the element's class
attribute value: 例如,元素的class
属性值:
' foo bar baz '
OR 要么
'foo bar baz '
Should both become a css selector: 两者都应成为CSS选择器:
'.foo.bar.baz'
Right now, I'm using: 现在,我正在使用:
String classCssSelector = "." + classProp.trim().replaceAll("\\s+", ".");
But I want to get rid of the leading hardcoded "." +
但是我想摆脱前面的硬编码"." +
"." +
and the trim()
and make it all one replaceAll
call. "." +
和trim()
并使其全部成为一次replaceAll
调用。
EDIT : 编辑 :
I used the regex provided in @anubhava's answer, but then wanted it to also match an already 'dotted' class like this: 我使用了@anubhava答案中提供的正则表达式,但随后希望它也可以匹配已经是“点状”的类,如下所示:
' foo bar baz '
The following regex works for both cases: 以下正则表达式适用于两种情况:
^(?!\.)| +(?= *\S)
You can use this regex in replaceAll
: 您可以在replaceAll
使用此正则表达式:
^ *| +(?= *\S)
Code: 码:
String classCssSelector = classProp.replaceAll("^ *| +(?= *\\S)", ".");
Explanation: 说明:
^ - Match beginning
^ * - Match 0 or more spaces at start
| - Alternation in regex
| + - Match 1 more spaces after `|`
(?= *\\S) - Lookahead to make sure there is at least one non-space character after matching
space in previous match
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.