Skip to content

Instantly share code, notes, and snippets.

@kevin-lee
Last active September 7, 2015 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevin-lee/f8913cdf03dad485daa5 to your computer and use it in GitHub Desktop.
Save kevin-lee/f8913cdf03dad485daa5 to your computer and use it in GitHub Desktop.
Take all the names and URLs from HTML
@daewon
Copy link

daewon commented Sep 5, 2015

조금 더 간단하게 수정해 봤습니다.
개인적으로 스칼라를 아주 좋아하지만, 루비 등 스크립트 언어에 비해서는 아직 불편한게 많네요(특히 json등을 다룰 때)

code

val text = """
<div class="content">
<h4>Some Header</h4>
<p><a href="https://some.url.com?blah=MORE-BLAH" class="inline">Test URL1</a><span class="highlighted">(something.else)</span><br>
<a href="https://another.url.com?dr=who" class="inline">Test URL2</a><span class="highlighted">(something.else)</span><br>
<a href="https://third.url.com?name=dontknow" class="inline">Test URL3</a><span class="highlighted">(something.else)</span></p>
          </div>
""".stripMargin

val aTagPattern = """<a\s+(?:[^>]*?\s+)?href="([^"]*)"\s*(?:[^>]*?\s*)?>([^"]*)<\/a>""".r.unanchored
text.split("[\\n]+") collect { case aTagPattern(url, name) => s"$name\n$url\n" } foreach println

result

Test URL1
https://some.url.com?blah=MORE-BLAH

Test URL2
https://another.url.com?dr=who

Test URL3
https://third.url.com?name=dontknow

@kevin-lee
Copy link
Author

@daewon 아주 간결하고, 불필요한 Option, Tuple사용도 없이 바로 String으로 만드셨군요. 😄 👍

@kevin-lee
Copy link
Author

@daewon 저도 사실 코드가 맘에 안들어서 for comprehension 써서 리팩토링 중이었거든요.

(for {
  line <- text.split("[\\n]+")
  aTagPattern(url, name) <- aTagPattern findAllMatchIn line
} yield (s"$name\n$url\n")) foreach println

@kevin-lee
Copy link
Author

근데 @daewon님 코드가 더 맘에 드네요. :)

@kevin-lee
Copy link
Author

루비는 JSON을 어떻게 다루나요? 혹시 루비 자체 데이터 타입으로 제공한다거나? 😲?

@daewon
Copy link

daewon commented Sep 7, 2015

@kevin-lee 이제야 확인을 했습니다. 보니까 저는 for comprehension이 훨씬 가독성이 좋네요 👍
루비에서 json은 그냥 hash로 1:1로 양방향 변환이 되니까(다이나믹 타입) 아주아주 편리합니다.
루비에서 hash의 위상이 엄청나게 높다보니 ㅎㅎ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment