Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 31-40 of 79 total

Ruby: Strip html tags from a string

str = "<html>This and <b>that</b> and <br />and <span class='something'>the other</span>?<html>"
puts str.gsub(/<\/?[^>]*>/, "")

Ruby: Count number of words in a string

class String
  def count_words
    n = 0
    scan(/\b\S+\b/) { n += 1}
    n
  end 
end

Match an html attribute

The goal of this expression is to match all "id" attributes of the "div" tags on a page

<div(?=\s)
(?:
  (?!\sid=|>)
  .
)* # Consume everything until finding " id=" or ">"
   # (">" is just for failing faster)

\sdiv=(?P<__quote>['"])? # Consume " div=" and save the quote type (' or ") if any

(?: # while
  (?! # next character isn't, 
    (?(__quote) # if a quote has been opened,
      (?P=__quote) # the closing quote ;
      |[\s>] # a space or ">" else,
    )
  )
  . # consume this character
)*


(?(__quote) # If we got a quote
  (?P=__quote)| # it must be closed
  (?=[\s>]) # else, the attribute is ended by a space or ">"
)

[^>]*> # Consume the rest of the tag

Testing for Exception message in Rails

e = assert_raise(RuntimeError) { my_code_that_raises }
assert_match(/Error message here/i, e.message)..

Variable-length negation

Everybody known the
<div[^>]*>

construction to match a tag. But how to match inside a tag ? We want something like:
<div>[^div]*</div>

but it don't work since [^div] has not this meaning ;)

This regexp do that (but don't manage nested markups, however).

<div>
(?:
  (?!</div>) # If not followed by </div>
  . # Match any character
)* # Non-capturing grouping
</div>

Netiquette: wrap lines

Netiquette say that your lines must not be longer that 80 letters. This regexp limit the size of a line at 80 letters without splitting a word

For example,

N'y a t-il pas quelque chose d'un peu grotesque dans le spectacle d'êtres humains tenant un miroir devant eux, et trouvant ce qu'ils y voient assez parfait pour démontrer qu'un Dessein Cosmique y tendait dès l'origine?

Will be transformed in:

N'y a t-il pas quelque chose d'un peu grotesque dans le spectacle d'êtres
humains tenant un miroir devant eux, et trouvant ce qu'ils y voient assez
parfait pour démontrer qu'un Dessein Cosmique y tendait dès l'origine?

s/([^\n]{0,80})\s/$1\n/mg

email validation regex

/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/ 		

Regular expression to match MySQL's DATETIME type

Matches MySQL built-in datetime type, for example, 2007-06-05 15:26:02
It also matches date type, i.e. 2007-06-05

/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/

Java: RegEx to Remove HTML Tags

// Ref: https://jalbum.net/forum/thread.jspa?forumID=7&threadID=971&messageID=6907

String noHTMLString = htmlString.replaceAll("\\<.*?\\>", "");

URL Regex

// description of your code here
A regular expression pattern that validates a URL string, either HTTP or HTTPS.

/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix


You can easily use it with validates_format_of in your Model...

For example, In a comment model, to check the :SiteURL on the comment creation:

class Comment < ActiveRecord::Base
    validates_format_of :SiteURL, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix, :on => :create
end


« Newer Snippets
Older Snippets »
Showing 31-40 of 79 total