How to check if a string contains a substring cont

2020-02-11 08:25发布

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!

标签: java regex
6条回答
手持菜刀,她持情操
2楼-- · 2020-02-11 08:29

Put it all into a string variable, say s, then do s.contains("{my string: }); this will return true if {my string: } is in s.

查看更多
三岁会撩人
3楼-- · 2020-02-11 08:36

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

return stringToSearch.replaceAll("\s", "").contains(
  stringToFind.replaceAll("\s", ""));
查看更多
贪生不怕死
4楼-- · 2020-02-11 08:43

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

查看更多
beautiful°
5楼-- · 2020-02-11 08:52

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 e.g.:

String myStr = "this is {my string: } ok";
if (myStr.trim().contains("{my string: }")) {
    //Do something.
} 
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-11 08:52

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)

查看更多
家丑人穷心不美
7楼-- · 2020-02-11 08:56

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. I.e. :

String searchedString = "this is {my string: } ok";
String stringToMatch = "{my string: }";
boolean foundMatch = searchedString.replaceAll(" ", "").contains(stringToMatch.replaceAll(" ",""));
查看更多
登录 后发表回答