我想使用来自用户的输入作为搜索某些文本的正则表达式模式.它有效,但我如何处理用户放置在正则表达式中有意义的字符的情况?例如,用户想要搜索Word (s)
:正则表达式引擎将(s)
作为一个组.我希望它像一个字符串一样对待它"(s)"
.我可以运行replace
用户输入并替换(
with \(
和)
with \)
但问题是我需要替换每个可能的正则表达式符号.你知道更好的方法吗?
假设你有一个字符串文字,里面有很多引号.你可以逃避所有这些,但这是一种痛苦,难以阅读.
在某些语言中,您可以这样做:
foo = '"Hello, World"';
Run Code Online (Sandbox Code Playgroud)
但是,在Java中,s ''
用于char
s,因此不能以String
这种方式使用它.有些语言有解决此问题的语法.例如,在python中,您可以这样做:
"""A pretty "convenient" string"""
Run Code Online (Sandbox Code Playgroud)
Java有类似的东西吗?
我试图弄清楚如何从字符串中提取子字符串,但该字符串包含一个括号,然后 Java 抱怨它没有包含在内,如果我尝试转义它,则会抱怨它不是有效的转义字符。
\n\n我有以下字符串:
\n\n[Monitor Status](/monitors#2972550?)] \xc2\xb7 [[Edit Monitor](/monitors#2972550/edit)] \xc2\xb7 [[Related Logs](/logs?query=)]\n%%%\n
Run Code Online (Sandbox Code Playgroud)\n\n我正在尝试提取 /monitors# 之后的数字。该数字位于两个地方,并且在两个地方始终相同,因此我只是尝试提取第一个数字。
\n\n以下是我目前拥有的:
\n\nPattern pattern = Pattern.compile("[Monitor Status]/monitors#(\\\\d+)"); \nMatcher matcher = pattern.matcher(monitorDetails);\nif (matcher.find())\n{\n String monitor_id = matcher.group(1);\n monitorDetailsContainer.setVisibility(View.VISIBLE);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n通过上面的内容,我没有(
] 和 /monitors 之间的内容,但是当我执行 Android Studio 时,会说unclosed group
. 如果我尝试转义斜杠,\\(
则会显示非法转义字符。
我期待得到的是2972550
.