将问号 (?) 替换为 (\\?)

发布于 2024-10-09 22:07:46 字数 372 浏览 6 评论 0原文

我正在尝试定义一个模式来匹配文本中带有问号(?)的文本。在正则表达式中,问号被认为是“一次或根本不”。 那么我可以用 (\\?) 替换文本中的 (?) 符号来解决模式问题吗?

String text = "aaa aspx?pubid=222 zzz";
Pattern p = Pattern.compile( "aspx?pubid=222" );
Matcher m = p.matcher( text );

if ( m.find() )
 System.out.print( "Found it." );
else
 System.out.print( "Didn't find it." );  // Always prints.

I am trying to define a pattern to match text with a question mark (?) inside it. In the regex the question mark is considered a 'once or not at all'. So can i replace the (?) sign in my text with (\\?) to fix the pattern problem ?

String text = "aaa aspx?pubid=222 zzz";
Pattern p = Pattern.compile( "aspx?pubid=222" );
Matcher m = p.matcher( text );

if ( m.find() )
 System.out.print( "Found it." );
else
 System.out.print( "Didn't find it." );  // Always prints.

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

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

发布评论

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

评论(2

锦欢 2024-10-16 22:07:46

您需要在正则表达式中将 ? 转义为 \\?,而不是在文本中。

Pattern p = Pattern.compile( "aspx\\?pubid=222" );

查看

您还可以使用quote Pattern 类的方法来引用正则表达式元字符,这样不必担心引用它们:

Pattern p = Pattern.compile(Pattern.quote("aspx?pubid=222"));

查看

You need to escape ? as \\? in the regular expression and not in the text.

Pattern p = Pattern.compile( "aspx\\?pubid=222" );

See it

You can also make use of quote method of the Pattern class to quote the regex meta-characters, this way you need not have to worry about quoting them:

Pattern p = Pattern.compile(Pattern.quote("aspx?pubid=222"));

See it

人疚 2024-10-16 22:07:46

在java中转义正则表达式任何文本的正确方法是使用:

String quotedText = Pattern.quote("any text goes here !?@ #593 ++ { [");

然后您可以使用quotedText作为正则表达式的一部分。
例如,您的代码应如下所示:

String text = "aaa aspx?pubid=222 zzz";
String quotedText = Pattern.quote( "aspx?pubid=222" );
Pattern p = Pattern.compile( quotedText );
Matcher m = p.matcher( text );

if ( m.find() )
    System.out.print( "Found it." ); // This gets printed
else
    System.out.print( "Didn't find it." ); 

The right way to escape any text for Regular Expression in java is to use:

String quotedText = Pattern.quote("any text goes here !?@ #593 ++ { [");

Then you can use the quotedText as part of the regular expression.
For example you code should look like:

String text = "aaa aspx?pubid=222 zzz";
String quotedText = Pattern.quote( "aspx?pubid=222" );
Pattern p = Pattern.compile( quotedText );
Matcher m = p.matcher( text );

if ( m.find() )
    System.out.print( "Found it." ); // This gets printed
else
    System.out.print( "Didn't find it." ); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文