简体   繁体   中英

python regular expression match comma

In the following string,how to match the words including the commas

  1. --

     process_str = "Marry,had ,a,alittle,lamb" import re re.findall(r".*",process_str) ['Marry,had ,a,alittle,lamb', '']
  2. --

     process_str="192.168.1.43,Marry,had ,a,alittle,lamb11" import re ip_addr = re.findall(r"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}",l) re.findall(ip_addr,process_str1)

    How to find the words after the ip address excluding the first comma only ie, the outout again is expected to be Marry,had ,a,alittle,lamb11

  3. In the second example above how to find if the string is ending with a digit.

In the second example, you just need to capture (using () ) everything that follows the ip:

 import re

 s = "192.168.1.43,Marry,had ,a,alittle,lamb11"
 text = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},(.*)", s)[0]
 // text now holds the string Marry,had ,a,alittle,lamb11

To find out if the string ends with a digit, you can use the following:

re.match(".*\d$", process_str)

That is, you match the entire string ( .* ), and then backtrack to test if the last character (using $ , which matches the end of the string) is a digit.

Find the words including the commas, that's how I understand this sentence:

>>> re.findall("\w+,*", process_str)
['Marry,', 'had', 'a,', 'alittle,', 'lamb']

ending with a didgit:

"[0-9]+$"

Hmm. The examples are not quite clear, but it seems in example #2, you want to only match text , commas, space-chars, and ignore digits? How about this:

re.findall('(?i)([a-z, ]+), process_str)

I didn't quite understand the "if the string is ending with a digit". Does that mean you ONLY want to match 'Mary...' IF it ends with a digit? Then that would look like this:

re.findall('(?i)([a-z, ]+)\d+, process_str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM