Discussion:
字元替換問題
(时间太久无法回复)
沒好事
2006-08-23 17:33:14 UTC
Permalink
假設在一個字串當中有著一些特殊符號,如: ",:?<>+_)(&^%$#!/

我想把他用空白字元給替換掉,請問怎樣的作法比較有效率呢?

我只會 String.replace(","," ").replace(";"," ").replace("?"," ")....

一直下去 orz

有在研究 Pattern 跟 Matcher,看得不是很懂 ( ̄□ ̄|||)a

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.116.96.181
愚者
2006-08-23 18:00:01 UTC
Permalink
※ 引述《NothingGood (沒好事)》之銘言:
: 假設在一個字串當中有著一些特殊符號,如: ",:?<>+_)(&^%$#!/
: 我想把他用空白字元給替換掉,請問怎樣的作法比較有效率呢?
: 我只會 String.replace(","," ").replace(";"," ").replace("?"," ")....
: 一直下去 orz
: 有在研究 Pattern 跟 Matcher,看得不是很懂 ( ̄□ ̄|||)a


當我歡樂地打開Regular expression的說明時,看到了這一個東東
http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html

POSIX character classes (US-ASCII only)
\p{Lower} A lower-case alphabetic character: [a-z]
\p{Upper} An upper-case alphabetic character:[A-Z]
\p{ASCII} All ASCII:[\x00-\x7F]
\p{Alpha} An alphabetic character:[\p{Lower}\p{Upper}]
\p{Digit} A decimal digit: [0-9]
\p{Alnum} An alphanumeric character:[\p{Alpha}\p{Digit}]
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 
\p{Graph} A visible character: [\p{Alnum}\p{Punct}]
\p{Print} A printable character: [\p{Graph}\x20]
\p{Blank} A space or a tab: [ \t]
\p{Cntrl} A control character: [\x00-\x1F\x7F]
\p{XDigit} A hexadecimal digit: [0-9a-fA-F]
\p{Space} A whitespace character: [ \t\n\x0B\f\r]



public class Regex {
public static void main(String[] args){
String s = "\\p{Punct}";
String content = "asdf\\sdfs\"df,:s?df<sdf>ds+f_sdf)"
+"dsf(sdfsad&^%$#!/";
System.out.println(content.replaceAll(s, " "));
}
}

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 163.26.34.213

Loading...