如何查找Java中的字符串中是否存在特殊字符

时间:2011-08-03 11:17:49

标签: java regex string

我想检查字符串是否包含#。 然后,如果它包含#,我想在#之后找到内容。

例如,

  • test#1 - 这应该归还给我1
  • test*1 - 这不应该返回任何内容。
  • test#123Test - 这应该返回123Test

请告诉我。提前完成。

2 个答案:

答案 0 :(得分:4)

我使用简单的字符串操作而不是正则表达式:

int index = text.indexOf('#');
return index == -1 ? "" : text.substring(index + 1);

(我假设“不应该返回任何内容”在这里意味着“返回空字符串” - 如果需要,您可以将其更改为返回null。)

答案 1 :(得分:2)

// Compile a regular expression: A hash followed by any number of characters
Pattern p = Pattern.compile("#(.*)");

// Match input data
Matcher m = p.matcher("test#1");

// Check if there is a match
if (m.find()) {

  // Get the first matching group (in parentheses)
  System.out.println(m.group(1));
}