简体   繁体   中英

How to check if a string contains a substring containing spaces?

Say I have a string like this in java:

"this is {my string: } ok"

Note, there can be any number of white spaces in between the various characters. How do I check the above string to see if it contains just the substring:

"{my string: }"

Many thanks!

If you are looking to see if a String contains another specific sequence of characters then you could do something like this :

String stringToTest = "blah blah blah";

if(stringToTest.contains("blah")){
    return true;
}

You could also use matches. For a decent explanation on matching Strings I would advise you check out the Java Oracle tutorials for Regular Expressions at :

http://docs.oracle.com/javase/tutorial/essential/regex/index.html

Cheers,

Jamie

If you have any number of white space between each character of your matching string, I think you are better off removing all white spaces from the string you are trying to match before the search. Ie :

String searchedString = "this is {my string: } ok";
String stringToMatch = "{my string: }";
boolean foundMatch = searchedString.replaceAll(" ", "").contains(stringToMatch.replaceAll(" ",""));

把它全部放入一个字符串变量,比如s,然后执行s.contains(“{my string:});如果{my string:}在s中,这将返回true。

For this purpose you need to use String#contains(CharSequence) .

Note, there can be any number of white spaces in between the various characters.

For this purpose String#trim() method is used to returns a copy of the string, with leading and trailing whitespace omitted.

For eg:

String myStr = "this is {my string: } ok";
if (myStr.trim().contains("{my string: }")) {
    //Do something.
} 

The easiest thing to do is to strip all the spaces from both strings.

return stringToSearch.replaceAll("\s", "").contains(
  stringToFind.replaceAll("\s", ""));

Look for the regex

\{\s*my\s+string:\s*\}

This matches any sequence that contains

  1. A left brace
  2. Zero or more spaces
  3. 'my'
  4. One or more spaces
  5. 'string:'
  6. Zero or more spaces
  7. A right brace

Where 'space' here means any whitespace (tab, space, newline, cr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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