【问题标题】:Check substring with spaces检查带空格的子字符串
【发布时间】:2014-05-13 11:30:35
【问题描述】:

我正在尝试从字符串中提取一些带有空格的数据。这是我的代码:

if (somestring.contains("LOOP with spaces")) {
    i++;
}   

是否有正则表达式来提取这个:我试过了,但没有用

somestring.contains("LOOP\swith\s spaces"))

【问题讨论】:

  • 为什么要使用正则表达式?只找到字符串有什么问题?
  • 不返回任何我使用的内容(“带空格的循环”)

标签: java regex string


【解决方案1】:

如果您想使用正则表达式作为参数,请改用matches

if (somestring.matches(".*LOOP\\swith\\sspaces.*")){

请注意,(1).* 表示任意数量的任意字符,(2)您需要转义 Java 中的反斜杠:\\ 被解释为 \

【讨论】:

  • 它在 Java 中对我有用。您要测试的字符串是什么?
  • @Bathsheba 可能是 OP 有多重空间并且想要像 .*LOOP\\s+with\\s+spaces.* 这样的东西。很难说清楚,因为问题没有说清楚。
  • 我使用的字符串是“INFO - LOOP with space : some other text goes in here on ever line”
  • @user3588388 那么你想做什么呢?检查字符串是否包含LOOP with spaces?或者提取LOOP with spaces - 提取常量字符串的意义何在?
  • 可能是因为“LOOP”和“Loop”不一样吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2010-12-16
  • 2017-08-19
相关资源
最近更新 更多