Regular expression in ruby

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

พยายามอ่านเรื่อง regular expression จาก http://www.thaijobmarket.com/regularex.html แต่ไม่ประสบความสำเร็จครับ เลยต้องรบกวนผู้รู้

ผมมี string อยู่ตัวหนึ่ง

s = “\192.192.1.107\FileRadioSp\032002\002-20020307004.mp3”

ต้องการใช้ regular expression ตัดให้เหลือแค่

“\192.192.1.107\FileRadioSp\032002”

โดยมีหลักการว่า ตัด string ที่อยู่หลัง \ ตัวสุดท้ายออกให้หมด รวมทั้งตัว \ เองด้วย

ผมพยายามทำโดยใช้คำสั่ง

o = s.gsub(/[*]$/,”) <- แต่ไม่สำเร็จแน่ๆ

ps. มีใครอยากเปิดสอน regular expression หรือเปล่าครับ :’( อยากเรียนมาก

sugree's picture

ของ python

re.sub(r'\\[^\\]*$','',s)
s = '\192.192.1.107\FileRadioSp\032002\002-20020307004.mp3'
#ต้องระวัง ไม่ใช้ string literal เป็น double quote ครับ เพราะมันจะไปพยายาม escape ตัวอักษรด้านหลัง
 
puts s
 
g = s.gsub(/\\[^\\]+$/,'')
 
puts g

ส่วนตัวผมไม่จำเป็นไม่ใช้ Regular Expression ความจริงมันดี แต่โค้ดก็จะอ่านยากถ้ามันซับซ้อนมากๆ

# str = "\\192.192.1.107\\FileRadioSp\\032002\\002-20020307004.mp3"
str = '\192.192.1.107\FileRadioSp\032002\002-20020307004.mp3'  
 
# ใช้ RegEx
matched = str[/(.*)\\/, 1]
puts "#{matched}"
 
# ไม่ใช้  อย่าง case นี้ก็ split ออกมาเป็น array เอา ง่ายดี
new_str = "\\" + str.split("\\")[1..-2] * "\\"
puts "#{new_str}"
apirak's picture

ระหว่างรอคำตอบผมใช้ split แบบคุณ zdk ไปแล้น ผมว่า

matched = str[/(.*)\/, 1]

ก็สะดวกดีครับ

ขอบคุณนะครับ :)

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น