How to use Regex to match anything but a period and a comma

I'm trying to do a match on things such as thomas. - any string ends up with a period or a comma.  How should I do it?  Thanks.
thomaszhwangAsked:
Who is Participating?
 
MichaelStaszewskiConnect With a Mentor Commented:
Try this.

[^.,]+

Open in new window

0
 
thomaszhwangAuthor Commented:
Shouldn't I use the escape? I tried the following, but it doesn't work...

[^\.\,]+

Open in new window

0
 
Pierre FrançoisConnect With a Mentor Senior consultantCommented:
Obviously: in regex: don't escape the dot inside of brackets [ ]. Never escape a comma.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
farzanjConnect With a Mentor Commented:
If you want to match lines that end with a comma or period use

[,.]$

Within [ ], you don't need to escape except for \[ and \]
0
 
MichaelStaszewskiConnect With a Mentor Commented:
Shouldn't I use the escape? I tried the following, but it doesn't work...

No, that is a character class. Did you try what I wrote exactly? What I wrote should do it. You can review character classes (and many other useful items) here.

http://www.regular-expressions.info/reference.html
0
 
käµfm³d 👽Connect With a Mentor Commented:
Obviously: in regex: don't escape the dot inside of brackets [ ]. Never escape a comma.
While it doesn't hurt anything (typically) to do so, you don't have to escape those particular characters within a character class.

Within [ ], you don't need to escape except for \[ and \]
...and the hyphen, if it does not occur as the first or last character of the class   ; )
0
 
whosbetterthanmeConnect With a Mentor Commented:
Another way might be:

my $s = 'Thomas.';

if ($s =~ m/(\.$)|(,$)/g) {
print "Found\n";
}
else {
print "Nope\n";
}
0
 
Terry WoodsConnect With a Mentor IT GuruCommented:
By "string" do you mean a single word, or an entire sentence, or a string?

Assuming you require a period or comma after the value you want, these might work for you:

If you want a single word:
\w+(?=[,.])

If you want a sentence:
[^.,?!]+(?=[,.])

If you want the entire string before the period or comma:
[^,]+(?=[,.])
0
 
thomaszhwangAuthor Commented:
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.