如何以$ kotlin开头的数字

发布于 2025-01-23 02:04:08 字数 224 浏览 2 评论 0原文

我将文档扫描到Kotlin,并有单词,数字,价值等...但是我只想要以$开头的值,并在此之后有2个小数点。带有其他字符串解析的子字符串?

编辑:我已经调查了Regex,现在我遇到的问题是我正在使用这条线

val reg = Regex("\$([0-9]*\.[0-9]*)")

来获取所有价格,但是 *的一部分。在说逃脱无效。但是,在其他语言中,这很好。

I scanned a document in to kotlin and it has words, numbers, values, etc... but I only want the values that start with a $ and have 2 decimal places after the .(so the price) do I use a combination of a substring with other string parses?

Edit: I have looked into Regex and the problem I am having now is I am using this line

val reg = Regex("\$([0-9]*\.[0-9]*)")

to grab all the prices however the portion of *. is saying Invalid escape. However in other languages this works just fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵情客 2025-01-30 02:04:08

您必须使用double \而不是单个。这是因为\是Regex和Kotlin/Java字符串中的逃生角色。因此,当\出现在字符串中时,Kotlin期望它之后是需要逃脱的角色。但是您并没有试图逃脱字符串的角色...您正在尝试逃脱正则角色。因此,您必须使用另一个后斜线逃脱后斜线,因此后斜线是计算出的字符串字面的一部分,可以通过Regex理解。

在美元符号之前,您还需要双\才能正确行事。从技术上讲,我认为这应该是三重\,因为$是Kotlin和Regex中的一个特殊角色,您想在这两个方面逃脱它。但是,如果没有可变名称或表达式遵循美元符号,Kotlin似乎足够聪明,可以猜测您要尝试做什么。我不会依靠这一点,而是使用三重逃生。

val reg = Regex("\\\$([0-9]*\\.[0-9]*)")

You have to use double \ instead of single . It's because the \ is an escape character both in Regex and in Kotlin/Java strings. So when \ appears in a String, Kotlin expects it to be followed by a character that needs to be escaped. But you aren't trying to escape a String's character...you're trying to escape a Regex character. So you have to escape your backslash itself using another backslash, so the backslash is part of the computed String literal and can be understood by Regex.

You also need double \ before your dollar sign for it to behave correctly. Technically, I think it should be triple \ because $ is a special character in both Kotlin and in Regex and you want to escape it in both. However, Kotlin seems smart enough to guess what you're trying to do with a double escape if no variable name or expression follows the dollar sign. Rather than rely on that, I would use the triple escape.

val reg = Regex("\\\$([0-9]*\\.[0-9]*)")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文