Java In language split() Method to split a string based on matching a given regular expression . Note the special characters in regular expressions .
After executing the following code, you can test The string is divided according to our expectation , no problem .
String test = "aasd#qwedc#sczxc"; String[] strArray = test.split("#");
But when we put “#” change into “.” Time , And there's a problem , After the following code is executed strArray Array is empty , What's going on ?
String test = "aasd.qwedc.sczxc"; String[] strArray = test.split(".");
because “.” Is a special character of a regular expression , A direct match is considered a regular expression , We can't get what we want . The right thing to do is to “.” Add in front “\\”, That's it , The code is as follows :
String test = "aasd.qwedc.sczxc"; String[] strArray = test.split("\\.");
such strArray The array is what we want .
Here are some special characters in regular expressions , These must be preceded when used as normal characters “\\”.
$ Matches the end of the input string . If set RegExp Object's Multiline attribute , be $ It also matches ‘\n’ or ‘\r’. To match $
Character itself , Please use \$.
( ) Mark the beginning and end of a subexpression . Subexpressions can be obtained for later use . To match these characters , Please use \( and \).
* Match previous subexpression zero or more times . To match * character , Please use \*.
+ Match previous subexpression one or more times . To match + character , Please use +.
. Match break \n Any single character other than . To match . Please use \.
[ Mark the beginning of a bracket expression . To match [, Please use \[.
? Match previous subexpression zero or once , Or indicate a non greedy qualifier . To match ? character , Please use \?.
\ Mark next character as or special character , Or literal character , Or backward reference , Or octal escape character . for example , 'n' Match character 'n'.'\n' Match newline . sequence
'\' matching "\", and '\(' Match "(".
^ Matches the start of the input string , Unless used in a bracket expression , In this case, it means that the character set is not accepted . To match ^ Character itself , Please use \^.
{ Mark the beginning of a qualifier expression . To match {, Please use \{.
| Indicate a choice between the two . To match |, Please use \|.
Technology
Daily Recommendation