0

Possible Duplicate:
Regex - Only letters?

I try to filter out alphabetics ([a-z],[A-Z]) from text.

I tried "^\w$" but it filters alphanumeric (alpha and numbers).

What is the pattern to filter out alphabetic?

Thanks.

Community
  • 1
  • 1
Billie
  • 8,938
  • 12
  • 37
  • 67

4 Answers4

2

To remove all letters try this:

void Main()
{
    var str = "some junk456456%^&%*333";
    Console.WriteLine(Regex.Replace(str, "[a-zA-Z]", ""));
}
ilivewithian
  • 19,476
  • 19
  • 103
  • 165
2

For filtering out only English alphabets use:

[^a-zA-Z]+

For filtering out alphabets regardless of the language use:

[^\p{L}]+

If you want to reverse the effect remove the hat ^ right after the opening brackets.

If you want to find whole lines that match the pattern then enclose the above patterns within ^ and $ signs, otherwise you don't need them. Note that to make them effect for every line you'll need to create the Regex object with the multi-line option enabled.

Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45
  • Using Sublime Text 2 the first example works as described, but the 2nd example doesn't. Don't know whether this is a quirk of the regex engine in ST2 though. – garyh Nov 15 '12 at 10:31
  • Probably difference between regex engines. I have tested them with [RegexHero](http://regexhero.net/tester/) which is a .NET based engine, and they work as expected. – Sina Iravanian Nov 15 '12 at 10:37
  • I tested them in Notepad++ too, and they work fine there too. – Sina Iravanian Nov 15 '12 at 10:52
  • 1
    +1 for the correct answer. For info: you don't need to put the Unicode property into a negated character class `[^\p{L}]`, you can just write `\P{L}` with an uppercase `P` to get the negated version. – stema Nov 15 '12 at 11:16
  • @stema Thanks. Learning something new everyday. – Sina Iravanian Nov 15 '12 at 12:09
0

try this simple way:

var result = Regex.Replace(inputString, "[^a-zA-Z\s]", "");

explain:

+ Matches the previous element one or more times.

[^character_group] Negation: Matches any single character that is not in character_group.

\s Matches any white-space character.

Ria
  • 10,237
  • 3
  • 33
  • 60
-1

To filter multiple alpha characters use

^[a-zA-Z]+$
garyh
  • 2,782
  • 1
  • 26
  • 28
  • It test it out thanks, but isn't it filter in? I mean, it filter everything BUT this? (a-zA-Z) – Billie Nov 15 '12 at 10:17
  • @user1798362 You question implied that `\w` did what you wanted but for alphanumerics, so don't be surprised if you get answers just replacing "alphanumerics" with "alpha" without magically knowing what else might be wrong with your code. – Rawling Nov 15 '12 at 10:24
  • 1
    Not sure I understand. Do you want to select everything _except_ alpha characters? – garyh Nov 15 '12 at 10:25