簡體   English   中英

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

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

我想檢查一個字符串是否包含# 然后,如果包含# ,我想在#之后找到內容。

例如,

  • test#1 —這應該返回我1
  • test*1這不應返回任何內容。
  • test#123Test —這應該返回123Test

請告訴我。 提前感謝。

我會使用簡單的字符串操作而不是正則表達式:

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

(我假設此處“不應返回任何內容”的意思是“返回空字符串”-如果需要,可以將其更改為返回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