简体   繁体   English

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

[英]How to find if a special character is present in a string in Java

I want to check whether a string contains # or not. 我想检查一个字符串是否包含# Then if it contains # , I want to find the content after # . 然后,如果包含# ,我想在#之后找到内容。

For example, 例如,

  • test#1 — This should return me 1 . test#1 —这应该返回我1
  • test*1 — This should not return anything. test*1这不应返回任何内容。
  • test#123Test — This should return 123Test . test#123Test —这应该返回123Test

Please let me know. 请告诉我。 Thanx in advance. 提前感谢。

I'd use simple string operations rather than a regular expression: 我会使用简单的字符串操作而不是正则表达式:

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

(I'm assuming "should not return anything" means "return empty string" here - you could change it to return null if you want.) (我假设此处“不应返回任何内容”的意思是“返回空字符串”-如果需要,可以将其更改为返回null 。)

// 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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM