【问题标题】:Java regex to replace whitespaces in css class string with dotsJava正则表达式用点替换css类字符串中的空格
【发布时间】:2015-02-20 11:15:31
【问题描述】:

给定一个 HTML 元素的 class 属性,我想生成一个适合 css 选择器的字符串。

比如元素的class属性值:

'  foo bar  baz '

或

'foo bar  baz '

都应该成为css选择器:

'.foo.bar.baz'

现在,我正在使用:

String classCssSelector = "." + classProp.trim().replaceAll("\\s+", ".");

但我想摆脱领先的硬编码 "." + 和 trim() 并使其全部成为一个 replaceAll 调用。

编辑:

我使用了@anubhava 的答案中提供的正则表达式,但随后希望它也匹配一个已经“加点”的类,如下所示:

'  foo bar  baz '

以下正则表达式适用于这两种情况:

^(?!\.)| +(?= *\S) 

【问题讨论】:

  • @anubhava:如果原始字符串中没有前导空格怎么办?
  • 它添加了多余的点......在这种情况下不起作用'foo bar baz'。
  • 它甚至会根据 OP 的输入在末尾添加点。

标签: java html css regex


【解决方案1】:

您可以在replaceAll 中使用此正则表达式:

^ *| +(?= *\S)

RegEx Demo

代码:

String classCssSelector = classProp.replaceAll("^ *| +(?= *\\S)", ".");

说明:

^         - 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

【讨论】:

  • 但它保留了尾随空格。 @Elist 你想删除尾随空格吗?
  • @AvinashRaj 是对的。我确实想删除它们,但我想这不能通过一个 replaceAll 调用来完成。
  • @Elist:没错,你可以在replaceAll 调用之后调用 trim,因为我们可以在replaceAll 的第二个参数中用点或"" 替换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2010-10-04
  • 2013-03-09
  • 1970-01-01
相关资源
最近更新 更多