import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import com.google.common.base.CharMatcher;
/**
* TODO 在此写上类的相关说明.<br>
* @author gqltt<br>
* @version 1.0.0 2021年11月11日<br>
* @see
* @since JDK 1.5.0
*/
public class CharMatcherDemo {
/**
* @param args
*/
public static void main(String[] args) {
replace();
collapse();
trimAndCollapse();
retain();
range();
}
/**
* 替换.
*/
static void replace() {
String stringWithLinebreaks = "This is an example\n"+
"of a String with linebreaks\n"+
"we want on one line";
String expected = "This is an example of a String with linebreaks we want on one line";
String scrubbed =
CharMatcher.breakingWhitespace().replaceFrom(stringWithLinebreaks, ' ');
Assert.assertThat(scrubbed, CoreMatchers.is(expected));
}
/**
* 压缩.
*/
static void collapse() {
String tabsAndSpaces = "String with spaces and tabs";
String expected = "String with spaces and tabs";
String scrubbed =
CharMatcher.whitespace().collapseFrom(tabsAndSpaces, ' ');
Assert.assertThat(scrubbed, CoreMatchers.is(expected));
}
/**
* 裁剪&压缩.
*/
static void trimAndCollapse() {
String tabsAndSpaces = " String with spaces and tabs";
String expected = "String with spaces and tabs";
String scrubbed =
CharMatcher.whitespace().trimAndCollapseFrom(tabsAndSpaces,' ');
Assert.assertThat(scrubbed, CoreMatchers.is(expected));
}
/**
* 保留.
*/
static void retain() {
String lettersAndNumbers = "foo989yxbar234";
String expected = "989234";
String retained = CharMatcher.javaDigit().retainFrom(lettersAndNumbers);
Assert.assertThat(expected, CoreMatchers.is(retained));
}
/**
* 字符范围.
*/
static void range() {
CharMatcher cm = CharMatcher.inRange('A','E');
Assert.assertThat(cm.retainFrom("aaaABbbccCdddDEeee"), CoreMatchers.is("ABCDE"));
}
}
Guava入门~CharMatcher
最新推荐文章于 2024-05-17 16:51:01 发布